From 3301bc9c2c265a4175070d5095543dade9688f4c Mon Sep 17 00:00:00 2001 From: Melove Gupta Date: Wed, 22 Oct 2025 13:03:44 +0530 Subject: [PATCH] Create is_power_of_three --- maths/is_power_of_three | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 maths/is_power_of_three diff --git a/maths/is_power_of_three b/maths/is_power_of_three new file mode 100644 index 000000000000..8f1151a0258d --- /dev/null +++ b/maths/is_power_of_three @@ -0,0 +1,39 @@ +""" +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: + """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()