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

前端 未结 3 1470
余生分开走
余生分开走 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: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 ;

提交回复
热议问题