Power of Three

Power of Three

Sergei Golitsyn

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

Given an integer n, return true if it is a power of three. Otherwise, return false.

An integer n is a power of three, if there exists an integer x such that n == 3x.

Example 1:

Input: n = 27
Output: true
Explanation: 27 = 33

Example 2:

Input: n = 0
Output: false
Explanation: There is no x where 3x = 0.

Example 3:

Input: n = -1
Output: false
Explanation: There is no x where 3x = (-1).

Solution:

One simple way of finding out if a number n is a power of a number b is to keep dividing n by b as long as the remainder is 0. This is because we can write

n​ = b^x
n = b×b×…×b

​Hence it should be possible to divide n by b x times, every time with a remainder of 0 and the end result to be 1.

  public boolean isPowerOfThree(int n) {
    if (n < 1){
      return false;
    }
     
    while (n % 3 == 0){
      n /= 3;
    }
    return n == 1;
  }


Mathematics

An important piece of information can be deduced from the function signature

In particular, n is of type int. In Java, this means it is a 4 byte, signed integer [ref]. The maximum value of this data type is 2147483647. Three ways of calculating this value are

  • System.out.println(Integer.MAX_VALUE);
  • Or use Google =)


Knowing the limitation of n, we can now deduce that the maximum value of n that is also a power of three is 1162261467.

Therefore, the possible values of n where we should return true are 3^0

3^0, 3^1,  ... 3^{19}

Since 3 is a prime number, the only divisors of 3^{19}  are 3^0,  3^1 ... 3^{19}

 therefore all we need to do is divide 3^{19} by n. A remainder of 0 means n is a divisor of 3^{19} and therefore a power of three.

  public boolean isPowerOfThree(int n) {
    return n > 0 && 1162261467 % n == 0;
  }


Report Page