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.)