Number of natural numbers from 1 to n, how many numbers contain 1

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.