Skip to content

Commit e79cebd

Browse files
authored
Create is_power_of_three
1 parent e2a78d4 commit e79cebd

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

maths/is_power_of_three

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Check if an integer is a power of three.
3+
4+
Time Complexity: O(log₃ n)
5+
Space Complexity: O(1)
6+
"""
7+
8+
def is_power_of_three(n: int) -> bool:
9+
"""Return True if n is a power of three (n > 0).
10+
11+
>>> is_power_of_three(1)
12+
True
13+
>>> is_power_of_three(3)
14+
True
15+
>>> is_power_of_three(9)
16+
True
17+
>>> is_power_of_three(27)
18+
True
19+
>>> is_power_of_three(2)
20+
False
21+
>>> is_power_of_three(0)
22+
False
23+
>>> is_power_of_three(-3)
24+
False
25+
>>> is_power_of_three(81)
26+
True
27+
"""
28+
if not isinstance(n, int):
29+
raise TypeError("n must be an integer")
30+
if n <= 0:
31+
return False
32+
while n % 3 == 0:
33+
n //= 3
34+
return n == 1
35+
36+
37+
if __name__ == "__main__":
38+
import doctest
39+
doctest.testmod()

0 commit comments

Comments
 (0)