Welcome, guest | Sign In | My Account | Store | Cart

Pretty good way to check if a number is a power of two or not.

Python, 7 lines
1
2
3
4
5
6
7
#Author: A.Polino

def is_power2(num):

	'states if a number is a power of two'

	return num != 0 and ((num & (num - 1)) == 0)

6 comments

Matteo Dell'Amico 13 years, 3 months ago  # | flag

Nice. Somebody might prefer it spelled as "return num and not num & (num - 1)".

A. Polino (author) 13 years, 3 months ago  # | flag

i'm happy you like it ;)

@matteo of course..but i think it's a little bit clearer in this way :)

david.gaarenstroom 13 years, 3 months ago  # | flag

If you want to do it even better, use this:

return ((num & (num - 1)) == 0) and num != 0

Which saves one check in most cases, since the check for 0 is only necessary if the other one evaluates to true... Also, you might want to check for a positive value, so this is probably better:

return ((num & (num - 1)) == 0) and num > 0
A. Polino (author) 13 years, 3 months ago  # | flag

you're right in the first sample (but it's really premature optimization)

in the second you're wrong; if you want to save the check for num <= 0 you should write

return num > 0 and ((num & (num - 1))

otherwise, 'num > 0' will never be executed unless num == 0

Sunjay Varma 13 years, 3 months ago  # | flag

How does this work? That's pretty cool.

david.gaarenstroom 13 years, 3 months ago  # | flag

Premature optimization is when you try to enhance your code before it actually works properly, in this case it's plain math.

And no, I am assuming you are using this function judiciously and aren't usually feeding it with illegal input (negative numbers), so it is really just a fall-back, so you can still best put it at last, but it does make less difference. But you are being a bit blunt calling me "wrong" here. If you are feeding it with random data, you should perhaps also check you are using integer input...

Created by A. Polino on Thu, 23 Dec 2010 (MIT)
Python recipes (4591)
A. Polino's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks