Skip to content

Commit b9c2b6e

Browse files
authored
Merge pull request prabhupant#393 from BGZ30/pow-of-two
Check power of two
2 parents 55685bf + 545a780 commit b9c2b6e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

algorithms/math/power_of_two.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
This simple code is to check if a given number is a poer of two or not.
3+
Method:
4+
if a number is a power of two, then its binary representation is (2^k).
5+
ex: 4 --> 2^2 --> 100 --> k = 2
6+
8 --> 2^3 --> 1000 --> k = 3
7+
16--> 2^4 --> 10000 --> k = 4
8+
9+
assume that n is a power of two, then (n-1)&(n) will be zero;
10+
ex:
11+
n = 8 --> (1000) , n-1 = 7 ---> (0111)
12+
performing bit (and) operation between both, then n&(n-1) = 0000
13+
14+
n = 12 --> (1100) , n-1 = 11 ---> (1011)
15+
performing bit (and) operation between both, then n&(n-1) = 1000
16+
17+
Conclusion:
18+
The result of the above bit "and" operation will be zero, ONLY if the given number is a pwoer of two.
19+
20+
NOTE:
21+
- Since Python considers 0 as "false", then we are gonna return the inversion of the result; i.e. return not(n&(n-1).
22+
- BUT If n = 0, the result will be zero indicating that 0 is a power of 2, wich is not true.
23+
So to fix that, we are going to perform an extra logical "and" operation with the oreginal number.
24+
"""
25+
26+
27+
def pow_of_two(n):
28+
return(n and (not(n&(n-1))))
29+
30+
for i in range(20):
31+
if pow_of_two(i):
32+
print(f"{i} is a power of 2.")
33+
else:
34+
print(f"{i} is NOT a power of 2.")

0 commit comments

Comments
 (0)