We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e2a78d4 commit c9c27d4Copy full SHA for c9c27d4
1 file changed
maths/is_power_of_three.py
@@ -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
15
+ >>> is_power_of_three(9)
16
17
+ >>> is_power_of_three(27)
18
19
+ >>> is_power_of_three(2)
20
+ False
21
+ >>> is_power_of_three(0)
22
23
+ >>> is_power_of_three(-3)
24
25
+ >>> is_power_of_three(81)
26
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