The problem is clear and simple. The For loop must be bad.
Using the Recursive method:
Define h (N) = from 1 to 9999 ..... 9999 (n 9) contains 1 of the number of digits. Defines the number of numbers that have 1 in the n digits of f (n).
By definition: H (n) =f (1) +f (2) +f (3) +....+f (n);
then f (1) =h (1) = 1;
F (2) =10^1+8*h (1).
F (3) =10^2+8*h (2).
F (4) =10^3+8*h (3).
......
The meaning is as follows: F (4) is a four-digit number, if the highest bit (thousand) is 1, then what is behind, this number must be 1, so it is 10^3.
If the highest bit is not 1, the highest bit can not be 0 (otherwise it will be 3 digits), so the highest bit has 8 options 2,3,4,5,6,7,8,9. This way, the low three bits must contain 1, otherwise there is no one. So multiply H (3).
Let's take an example to find the number of 1 numbers between 1 and 2345.
2345=h (1) +h (2) +h (3) part of +h (4).
The key is how a part of H (4) should be asked. The definition P (4,2) represents a four-digit number and contains 1 of the number if the high is less than 2. P (4,2) =10^3+p (3,3); p (3,3) indicates the number of three digits in the 3-digit number with the highest point less than 1.
Number of natural numbers from 1 to n, how many numbers contain 1