Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions maths/is_power_of_three.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
Check if an integer is a power of three.

Time Complexity: O(log₃ n)
Space Complexity: O(1)
"""


def is_power_of_three(n: int) -> bool:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: n

"""Return True if n is a power of three (n > 0).

>>> is_power_of_three(1)
True
>>> is_power_of_three(3)
True
>>> is_power_of_three(9)
True
>>> is_power_of_three(27)
True
>>> is_power_of_three(2)
False
>>> is_power_of_three(0)
False
>>> is_power_of_three(-3)
False
>>> is_power_of_three(81)
True
"""
if not isinstance(n, int):
raise TypeError("n must be an integer")
if n <= 0:
return False
while n % 3 == 0:
n //= 3
return n == 1


if __name__ == "__main__":
import doctest

doctest.testmod()