Fencepost error. The spec says inclusive, and your C-style for loop does not include 1e6. Use a Perl-style foreach loop and you would be unlikely to make the same mistake.
But still this one is faster to do with pen and paper. Convince yourself of the following:
- The total contributions from the 7'th (and higher) digits is the 1 in 1_000_000.
- For each given digit from the first through the sixth, there are 100_000 times that it is 0, 100_000 times it is 1, and so on up to 100_000 times it is 9.
- The answer is therefore 1 + 6*(0+1+2+3+4+5+6+7+8+9)*100_000.
- Therefore the answer is 27_000_001.
Now with this insight, a good exercise would be to write Perl code that efficiently calculates the sum of all of the digits in a range of integers. (Hint: Break things up by digit, and try to count how many you are going to have of each kind first.)
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|