What is the fastest (in asymptotic worst-case time complexity) algorithm for determining if a sum of arbitrary positive integers is a power of two?
Asked
Active
Viewed 78 times
-3
-
What operations are you allowed to use? – Mureinik Nov 28 '14 at 17:57
-
@RenéG That doesn't really answer the question. For instance, is addition considered to be constant-time, regardless of the size of the operands? – Sneftel Nov 28 '14 at 18:00
2 Answers
2
One cute bit twiddling trick is to test if x&(x-1)
is equal to 0.
Note that you need to decide what to do if x is equal to 0, this test will mark 0 as a power of 2 so you may want an exception for this case.

Peter de Rivaz
- 33,126
- 4
- 46
- 75
1
Subtract 1 from the sum and perform a bitwise AND with the original number. Powers of 2 will have a result of 0.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358