File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 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." )
You can’t perform that action at this time.
0 commit comments