Power of Three in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to check whether the number is the power of 3 or not. So if the number is like n = 27, that is the power of 3, the result will be true, if n = 15, it will be false.

To solve this, we will follow these steps −

  • We will use the Logarithm to solve this
  • if [log10(n) / log10(3)] mod 1 == 0, then it will be power of three, otherwise not

Example

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution(object):
   def isPowerOfThree(self, n):
      """
      :type n: int
      :rtype: bool
      """
      if not n or n<0:
         return False
      return (math.log10(n)/ math.log10(3)) % 1 == 0
ob1 = Solution()
print(ob1.isPowerOfThree(27))
print(ob1.isPowerOfThree(15))
print(ob1.isPowerOfThree(9)

Input

27
15
9

Output

true
false
true
raja
Updated on 28-Apr-2020 10:52:30

Advertisements