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 77 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
- 32,339
- 4
- 44
- 73
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
- 740,318
- 145
- 1,296
- 1,325