The ideal power of two between two numbers

How can I find the ideal strength of two between two numbers? Input example: 0 and 10 Output: 2, 4, 8

+1
source share
6 answers

Well, the interesting part: โ€œHow to get a maximum degree of 2 that is less than or equal to my upper boundโ€ and the same for the least degree of 2 that is greater than or equal to my lower bound.

And itโ€™s easy to do without loops. For 32-digit unsigned numbers:

floor(x):   ; floor power of 2
    x = x | (x >> 1)
    x = x | (x >> 2)
    x = x | (x >> 4)
    x = x | (x >> 8)
    x = x | (x >> 16)
    return x - (x >> 1)

ceil(x):   ; ceiling power of 2
    x = x - 1
    x = x | (x >> 1)
    x = x | (x >> 2)
    x = x | (x >> 4)
    x = x | (x >> 8)
    x = x | (x >> 16)
    return x + 1

You wonโ€™t be able to go around the loop to print numbers, but, well, good.

+1
source

, 1 , , x, . , 1 , , y. 2 x + 1 2 x + 2..., 2 y - ,

+3

, :

0  = 00000000
10 = 00001010

=>

     00000001 (1)
     00000010 (2)
     00000100 (4)
     00001000 (8)

, , , , , . , , , , , .

+1

, 0?

0

:

  • For example n1 = start_of_range,n2 = end_of_range.
  • Find out how many bits are needed to represent n1. Name him b.
  • Now 2**bwill be the next power of two after n1.
  • From this it is easy to calculate the full power of the two ups n2.

Python code example:

#!/usr/bin/python
def get_bits(n):
    b = 0
    while n:
        n = n / 2
        b += 1
    return b

def get_power_of_two_in_range(n1, n2):
    b = get_bits(n1)
    x = 2**b
    res = []
    while x < n2:
        res.append(x)
        x = x * 2
    return res

def main():
    print get_power_of_two_in_range(0, 10)

if __name__ == '__main__':
    main()
0
source
int first=0; //**first number which is a complete power of 2 in the range!**
 for(i=low;i<high;i++){
  if(2i==(i^(i-1)+1)){
   first=i;
   break;
  }
 }

while(first!=0){
 print first;
 first*=2;
 if(first>high){
  break;
}
}
0
source

All Articles