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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With