Clever thinking: power of 2

Xiao Ming started learning binary conversion to decimal, which use the power of two (2 to the power of 3 is 3 multiplied by 2), he think this is very interesting. Since by a power of 2 can be obtained by adding the tens, then in turn, whether a decimal number can be obtained by adding the power of a number 2 it?

Xiao Ming began to study up, he first lists all the powers of 2: 1,2,4,8,16,32,64 .......

4=1+1+1+1

4=1+1+2

4=2+2

4=4

4 There are four methods

7=1+1+1+1+1+1+1

7=1+1+1+1+1+2

7=1+1+1+2+2

7=1+1+1+4

7=1+2+2+2

7=1+2+4

There are 76 ways

1 + 2 + 4 + 4 + 2 and that equation is the same, because they have the same composition.

Now Bob wants to know, given a decimal number (not more than 10,000), how many can write, with a number of powers of 2 for the sum formula.

Ideas:

1. If n is odd, the f [n] = f [n-1] (1 a must be divided out, so that it is equal to the result of the result of an even number n-1)

2. If n is even, it is considered a split with and without a two cases:

(1) with a 1: number of planting this case F [n-1] (i.e. n-1 of the odd result)

(2) Without a: a case where this case seeding number of f [n / 2] (very clever, points out without an affirmative several branching off at each of several is even, this may be equivalent to several n / 2, because the points are divided by 2 out of the number is not that n / 2 points out of a few do?)

In conclusion: There recursion formulas: when n is odd, f [n] = f [n-1]; n is even, f [n] = f [n-1] + f [n / 2];

Also, note 1 n ==, direct initialization f [1] = 1.

#include <cstdio>
int f[1010];

int main(){
    int n;
    scanf("%d", &n);
    f[1] = 1;
    for(int i = 2; i <= n; i++) {
        if(i % 2 != 0) f[i] = f[i - 1];
        else f[i] = f[i-1] + f[i/2];
    }
    printf("%d\n",f[n]);
    return 0;
}

Guess you like

Origin www.cnblogs.com/baoyihan/p/11067629.html