Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding if a number is a power of 2

Tags:

Just out of curiosity, how can you tell if a number x is a power of two (x = 2^n) without using recursion.

Thanks

like image 566
Kartik Avatar asked Feb 11 '11 03:02

Kartik


People also ask

How do you check if a number is a power of something?

A simple solution is to repeatedly compute powers of x. If a power becomes equal to y, then y is a power, else not.

How do you find the power of 2 in C++?

pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function. then two numbers are passed. Example – pow(4 , 2); Then we will get the result as 4^2, which is 16.

How do you check if a number is a power of 10?

Number is a power of 10 if it's equal to 10, 100, 1000 etc. 1 is also 0-th power of 10. Other numbers like 2, 3, 11, 12 etc. are not powers of 10.


1 Answers

One way is to use bitwise AND. If a number $x is a power of two (e.g., 8=1000), it will have no bits in common with its predecessor (7=0111). So you can write:

($x & ($x - 1)) == 0 

Note: This will give a false positive for $x == 0.

like image 125
dan04 Avatar answered Sep 29 '22 10:09

dan04