Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the simplest way to test whether a number is a power of 2 in C++?

I need a function like this:

// return true if 'n' is a power of 2, e.g. // is_power_of_2(16) => true   // is_power_of_2(3) => false bool is_power_of_2(int n); 

Can anyone suggest how I could write this?

like image 955
Ant Avatar asked Sep 20 '08 14:09

Ant


People also ask

How do you test if a number is a power of 2 in C?

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 find the nearest number to the power of 2 in C?

next = pow(2, ceil(log(x)/log(2))); This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power.

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

If (x & (x-1)) is zero then the number is power of 2. For example, let x be 8 ( 1000 in binary); then x-1 = 7 ( 0111 ). This outputs the bit is power of 2 . This outputs the bit is not power of 2 .


2 Answers

(n & (n - 1)) == 0 is best. However, note that it will incorrectly return true for n=0, so if that is possible, you will want to check for it explicitly.

http://www.graphics.stanford.edu/~seander/bithacks.html has a large collection of clever bit-twiddling algorithms, including this one.

like image 83
Anonymous Avatar answered Oct 22 '22 01:10

Anonymous


A power of two will have just one bit set (for unsigned numbers). Something like

bool powerOfTwo = !(x == 0) && !(x & (x - 1)); 

Will work fine; one less than a power of two is all 1s in the less significant bits, so must AND to 0 bitwise.

As I was assuming unsigned numbers, the == 0 test (that I originally forgot, sorry) is adequate. You may want a > 0 test if you're using signed integers.

like image 41
Adam Wright Avatar answered Oct 21 '22 23:10

Adam Wright