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 :
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
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=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<
Hope it helps!