This Python program reads a number from the user and checks whether it is a power of 3.
Powers of 3 include: 3, 9, 27, 81, 243, ...
The program uses repeated division to determine if the number can be reduced to 1 by dividing by 3.
def is_power_of_3(n: int) -> bool:
if n < 1:
return False
while n % 3 == 0:
n //= 3
return n == 1
# Read number from user
num = int(input("Enter a number: "))
if is_power_of_3(num):
print(f"{num} is a power of 3.")
else:
print(f"{num} is not a power of 3.")
243 is a power of 3.
- The input number is checked to ensure it’s greater than zero
- The program repeatedly divides the number by 3
- If the result eventually becomes 1, the number is a power of 3
- Otherwise, it is not