Suppose you are given two positive integers, n and m. How would you determine whether n is a power of m?
Check if \(\log_m n\) is an integer
Ah brilliant - I'm so slow, thanks!
Ask yourself: can n be written in the equivalent form m^x, where x is a positive exponent?
Consider below expression : \[m^a = n\] Here, \(a\) is called the logarithm of \(n\) relative to the base \(m\). This is the definition of lagarithm.
n=25 is equivalent to 5^2, where 5 is our " m "
Yea, I was looking at this puzzle in a programming context, and it didn't even occur to me to use logs lol
Remember logarithm = exponent
so whenever you're dealing with exponents/powers, you're also dealing with logarithms
I was thinking of recursively dividing n by m and checking the end result, but logs are much cleaner
If you have a log function implemented in your language, then yeah could use it directly :)
Thanks!
Do you have an easy way to check if the result will be an integer ?
i mean, in ur language
Sec, I'll post the solution in a moment
Okie :)
from math import log class Solution(object): def isPowerOfThree(self, n): try: return log(n, 3).is_integer() except ValueError, AttributeError: return False hmm this is failing on 243, 3 because the built in log is returning 4.999999999999
Haha, there must be some nice way to get 5 out of 4.999999
Hmm I need to use the Decimal class I guess
I hate when this happens with rounding and what not
it always happens with floating point numbers, has to do with how the computer stores these floats
I think it would be easier to implement your own function by recursively dividing. Here you would be messign with only integers and don't have to worry about rounding
class Solution(object): def isPowerOfThree(self, n): if n == 0: return False while n % 3 == 0: n /= 3 return n == 1
I just needed the power of three for the puzzle, was generalizing for other cases lol
Here's another approach lol class Solution(object): def isPowerOfThree(self, n): return n in (3**x for x in range(41))
too slow when n isn't a power of 3
you're assuming the power is between 0 and 41 is it ?
hahah yeah
but this would generate all 41 powers of 3 in case of mismatches whereas the first solution would exit out as soon as it realized it's not a match
You can make it fast by first creating a file with powers of 3, and loading the file in your function
lol yea, anyway we're overthinking this, I'll see if there are other puzzles
Join our real-time social learning platform and learn together with your friends!