Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most programatically efficient way to determine if a number is a power of 2?

Just a simple of boolean true/false that is very efficient would be nice. Should I use recursion, or is there some better way to determine it?

like image 730
Skylion Avatar asked Sep 09 '13 00:09

Skylion


People also ask

How do you quickly check if a number is a power of 2?

Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

How do you find what power of 2 A number is?

A simple method for this is to simply take the log of the number on base 2 and if you get an integer then the number is the power of 2.

How do you determine if a number is a power of another number?

Algorithm to Check IF a Number is Power of Another NumberFind the log of a base b and assign its integer part to variable x. Also, find the b to the power x and assign it to another variable y. Check if y is equal to a then a is a power of another number b and print a is the power of another number b.


1 Answers

From here:

Determining if an integer is a power of 2

unsigned int v; // we want to see if v is a power of 2
bool f;         // the result goes here 

f = (v & (v - 1)) == 0;

Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:

f = v && !(v & (v - 1));

Why does this work? An integer power of two only ever has a single bit set. Subtracting 1 has the effect of changing that bit to a zero and all the bits below it to one. AND'ing that with the original number will always result in all zeros.

like image 55
Mitch Wheat Avatar answered Sep 18 '22 16:09

Mitch Wheat