# checking if a number if a power of 2

• 03-26-2009
-EquinoX-
checking if a number if a power of 2
Here's my code:

Code:

` ((num & (num - 1)) == 0)`
is this true? I tried it and it doesn't work as it's supposed to be. So is there another easier way?
• 03-26-2009
whiteflags
Check if the square root is a whole number.
• 03-26-2009
matsp
It should work. What numbers are you using?

--
Mats
• 03-26-2009
brewbuck
Quote:

Originally Posted by whiteflags
Check if the square root is a whole number.

And thus, 25 is a power of 2?
• 03-26-2009
-EquinoX-
I am trying to use 3
• 03-26-2009
matsp
Quote:

Originally Posted by -EquinoX-
I am trying to use 3

And what result to you expect, and how is that different from what you get? 3 is not a power of 2.

--
Mats
• 03-26-2009
-EquinoX-
oh nvm.. I found my self a stupid little mistake :D
• 03-26-2009
whiteflags
Quote:

Originally Posted by brewbuck
And thus, 25 is a power of 2?

Isn't it? 5 squared...
• 03-26-2009
sean
Power of two means two raised to a power, not a number raised to the second power. It's 2^x not x^2.

edit: The reason that first equation works is that any power of a number will be 1000 in that number system. 10, 100, 1000 are all powers of ten in the base-ten system. In base-two, they are all powers of two. Subtract one, and there will be a one in place of all the zeroes. 100 - 1 = 011. 100 & 011 = 0.
• 03-27-2009
iMalc
Quote:

Originally Posted by whiteflags
Isn't it? 5 squared...

... Making it a power of 5.

• 03-27-2009
vart
Quote:

Originally Posted by iMalc
... Making it a power of 5.

Which reminds me suddenly:

"Power of 3
Make us free,
Power of 3
Make us free..."

(c) Charmed

iMalc, do you need some power of 3 to reach him remotely? ;)