Even if the answer of @Chris is right, I'd like to share mine :)
To check the power p of a number n, you can convert this number to the base p and check if the first digit (on the left) is 1, and the remaining digits are 0.
x = 3**8
y = x - 1
z = x - 9
a = 30
def ternary (n):
if n == 0:
return '0'
nums = []
while n:
n, r = divmod(n, 3)
nums.append(str(r))
return ''.join(reversed(nums))
def is_power_of_3(n):
nstr = ternary(n)
return nstr[0] == '1' and int(nstr[1:]) == 0
print("x = {} {}\ny = {} {}\nz = {} {}\na = {} {}".format(ternary(x), is_power_of_3(x), ternary(y), is_power_of_3(y), ternary(z), is_power_of_3(z), ternary(a), is_power_of_3(a)))
I gave 4 example, only the x is a power of 3
Output:
x = 100000000 True
y = 22222222 False
z = 22222200 False
a = 1010 False