326 Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up: Could you do it without using any loop / recursion?
The Idea: 3^i = x, solve for i, we get the algebraic expression log_3(x) = i. So we're solving for the power i. Now if this power is an integer, then we know it is an integer power of 3, and we return true. One of the problems I found was that
log_3(243)returns 4.99999999999, while the symbolic solution should be 5.0. To account for these errors we account for some small delta, and so the integer difference must be smaller than or equal to delta.
Complexity: O(1) time and space
def isPowerOfThree(self, n):
:type n: int
if n <= 0:
sol = math.log(n, 3)
delta = .0000000001
return sol - int(sol + delta) <= delta