Search code examples
pythonpython-3.xmathlogarithm

Logarithm to base 3 in python


I am trying to find the logarithm of a number to base 3 using python.

Here is the problem :

https://leetcode.com/problems/power-of-three/description/

I am using this code:

import math
math.log(k,3)

However, it is failing for some test cases like (there are some more test cases):

math.log(243,3)

#output
4.999999999999999

math.log(59049,3)

#output
9.999999999999998

I do not want to use round() as it will round other numbers which are not the powers of 3.

Here is the full code which I am using:

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        import math
        k = abs(n)
        if n<=0:
            return False
        return math.log(k,3) == int(math.log(k,3))

Note: I am looking for solutions involving logarithms. Please feel free to ask for any clarifications.


Solution

  • This is just typical floating-point error. Recall that when you write math.log(x, 3), Python is actually calculating something like math.log(x) / math.log(3), with both (natural) log calculations and the division having to be rounded to the nearest float.

    But if you do your math with int instead of float, exactness is preserved.

    def is_power_of_three(n):
        if n <= 0:
            return False
        while n > 1:
            n, r = divmod(n, 3)
            if r != 0:
                return False
        return n == 1
    

    This checks if you can divide n by 3 (without remainder) until the result is 1.