Number of ways to write n as a sum of powers of 2

前端 未结 3 1459
余生分开走
余生分开走 2021-02-11 03:45

Is there any algorithm to find out that how many ways are there for write a number for example n , with sum of power of 2 ?

example : for 4 there are four ways :

相关标签:
3条回答
  • 2021-02-11 04:33

    A recursive definition of the sequence (from Peter's link to A018819):

    f(n) = 1 if n = 0, Sum(j = 0..[n/2], f(j)) if n > 0 http://mathurl.com/nuaarfm.png

    0 讨论(0)
  • 2021-02-11 04:44

    Suppose g(m) is the number of ways to write m as a sum of powers of 2. We use f(m,k) to represent the number of ways to write m as a sum of powers of 2 with all the numbers' power is less than or equal to k. Then we can reduce to the equation:

    if m==0 f(m,k)=1;    
    if k<0 f(m,k)=0;    
    if k==0 f(m,k)=1;    
    if m>=power(2,k) f(m,k)=f(m-power(2,k),k)+f(m,k-1);//we can use power(2,k) as one of the numbers or not.    
    else f(m,k)=f(m,k-1);
    

    Take 6 as an example:

    g(6)=f(6,2)
    =f(2,2)+f(6,1)
    =f(2,1)+f(4,1)+f(6,0)
    =f(0,1)+f(2,0)+f(2,1)+f(4,0)+1
    =1+1+f(0,1)+f(2,0)+1+1
    =1+1+1+1+1+1
    =6
    

    Here is the code below:

    #include<iostream>
    using namespace std;
    
    int log2(int n)
    {
        int ret = 0;
        while (n>>=1) 
        {
            ++ret;      
        }
        return ret;
    }
    
    int power(int x,int y)
    {
        int ret=1,i=0;
        while(i<y)
        {
            ret*=x;
            i++;
        }
        return ret;
    }
    
    int getcount(int m,int k)
    {
        if(m==0)return 1;
        if(k<0)return 0;
        if(k==0)return 1;
        if(m>=power(2,k))return getcount(m-power(2,k),k)+getcount(m,k-1);
        else return getcount(m,k-1);
    
    }
    
    int main()
    {
        int m=0;
        while(cin>>m)
        {
            int k=log2(m);
            cout<<getcount(m,k)<<endl;
        }
        return 0;
    }
    

    Hope it helps!

    0 讨论(0)
  • 2021-02-11 04:47

    You want to find the number of ways in which you can express a number as the sum of the power of 2. firstly you need to find the number set bits in that particular number because the number of the set bit will give us the minimum numbers required to express it as the sum of the power of 2. The maximum numbers required to express it as a sum of the power of 2 will the number itself because you can express it as a sum of 1 ( because 2 the power 0 is 1). example: 5 can be expressed as ( 1+1+1+1+1)

    hence the total number of ways to express a number as the power of 2 is simply given by the formula --> let the no be x ( x - no of set bits in x ) + 1 ; for example, let the number be 17 then the no of set bits in 17 is 2 hence the no of ways are ( 17 - 2 ) + 1 = 16 ;

    0 讨论(0)
提交回复
热议问题