Power of Three

Decide whether a whole number is 1, 3, 9, 27 or another power of three.

Given an integer n, return true if it is a power of three, that is, n = 3k for some whole number k ≥ 0. Otherwise, return false.

Example 1
Input: n = 27
Output: true
Explanation: 27 = 3 × 3 × 3.
Example 2
Input: n = 0
Output: false
Example 3
Input: n = 45
Output: false
Explanation: 45 = 3 × 3 × 5.
Solution

The Idea

Start with 1 and keep tripling: 3, 9, 27, 81, 243, and so on. The numbers on that list are the powers of three. The starting 1 belongs to it as 30, before any tripling. The number 27 is on the list, while 45 falls between 27 and 81 and is not.

A list works for small numbers, but how do you tell for a number like 1,162,261,467 without writing out every power up to it? Go backwards. If 27 was made by tripling 1 three times, then dividing 27 by 3 three times must lead back to 1.

Dividing out threes. In the row labelled Example 1, 27 becomes 9, 3 and 1, with remainder 0 each time until 1 % 3 = 1, so 27 ends at 1: true. In the row labelled Example 3, 45 becomes 15 and 5, and 5 % 3 = 2 stops it, so 45 ends at 5: false.

The picture shows both numbers being taken apart. Under each box is its remainder after dividing by 3, written with Java's % operator: 27 % 3 = 0 means 3 goes into 27 with nothing left over. In the row labelled Example 1, the remainder stays 0 through 27, 9 and 3, and the last box, 1, is where the dividing stops.

The row labelled Example 3 starts the same way: 45 and 15 both divide evenly. Then 5 % 3 = 2, so no more threes come out, and 5 is left over. That 5 is the factor in 45 = 3 × 3 × 5 that is not a 3.

So a positive number is a power of three exactly when taking out every factor of 3 leaves 1. Anything else left over, like the 5, is a factor that no amount of tripling can produce.

Solution Approach

Three choices turn the dividing into code: how to take out the threes, what to do with 0 and negative numbers, and why the code divides n down instead of multiplying a power up. After those come two shortcuts, one based on logarithms that rounding breaks and one optional check that needs no loop.

Taking out the threes

When should the dividing stop? A loop divides n by 3 for as long as n % 3 is 0. The first nonzero remainder means no 3 is left inside n. At that point the answer is simply whether n equals 1. For 27 that happens after three passes, and for 1 the loop never runs at all.

Zero and negative numbers

What happens with Example 2, where n is 0? Since 0 % 3 is 0 and 0 / 3 is still 0, the loop would divide forever without changing anything. So the method returns false for any n below 1 before the loop starts. Tripling 1 never gives a negative number either, so -27 is ruled out by the same check.

Dividing instead of multiplying

Why not build the powers instead, multiplying by 3 from 1 until the product reaches or passes n? For n = Integer.MAX_VALUE, which is 2,147,483,647, the products climb to 319 = 1,162,261,467, still below n. The next one, 320 = 3,486,784,401, does not fit in an int.

Java does not stop there. It wraps the product around to -808,182,895, which is still below n, so that loop goes on with a number unrelated to 320. Dividing has no such problem: each pass makes n smaller, so it always stays inside the range an int can hold.

Why logarithms do not work

Could a formula answer at once? If n = 3k, then k = log(n) / log(3), so one idea is to compute Math.log(n) / Math.log(3) and check for a whole number. The trouble is that Math.log returns a double, a decimal value rounded to about 16 digits. For 243 = 35, the quotient comes out as 4.999999999999999, so 243 is rejected. The same happens for 59,049 and 1,594,323.

Optional: a check without a loop

Is there an exact shortcut? The number 1,162,261,467 is 319, the largest power of three below Integer.MAX_VALUE. Since 3 has no whole factors besides 1 and itself, 319 is nineteen threes multiplied together and nothing else. A number that divides it evenly must be made of some of those threes, so it is one of 30 up to 319.

That gives a one-line test: n > 0 && 1162261467 % n == 0. The number 45 fails it, because the 5 inside 45 is not among the threes. The n > 0 part matters: 1162261467 % -27 is also 0, so without it -27 would pass.

Java Solution

The method isPowerOfThree works in these steps:

  1. First, check whether n is less than 1. If it is, return false at once, which covers 0 and every negative number.
  2. Then a while loop runs as long as n % 3 is 0, and each pass takes one factor of 3 out with n /= 3.
  3. When the loop stops, n has no factor of 3 left. Return n == 1, which is true for a power of three and false when another factor, like the 5 in 45, remains.

The class also holds isPowerOfThreeNoLoop, the one-line divisor test, so each line of output compares the two.

The main method runs the three examples, then 1, 243, -27, 319, Integer.MAX_VALUE and Integer.MIN_VALUE.

Java
public class PowerOfThree {

    public static boolean isPowerOfThree(int n) {
        if (n < 1) {
            return false;            // 0 and negatives are never powers of three
        }
        while (n % 3 == 0) {
            n /= 3;                  // take out one factor of 3
        }
        return n == 1;               // anything but 1 is a factor other than 3
    }

    // 3^19 = 1162261467 is the largest power of 3 that fits in an int.
    public static boolean isPowerOfThreeNoLoop(int n) {
        return n > 0 && 1162261467 % n == 0;
    }

    public static void main(String[] args) {
        int[] tests = {27, 0, 45, 1, 243, -27, 1162261467, Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int n : tests) {
            System.out.println("n = " + n + ": " + isPowerOfThree(n)
                    + " (no loop: " + isPowerOfThreeNoLoop(n) + ")");
        }
    }
}

Running it prints:

Output
n = 27: true (no loop: true)
n = 0: false (no loop: false)
n = 45: false (no loop: false)
n = 1: true (no loop: true)
n = 243: true (no loop: true)
n = -27: false (no loop: false)
n = 1162261467: true (no loop: true)
n = 2147483647: false (no loop: false)
n = -2147483648: false (no loop: false)

The lines for 27, 0 and 45 match the three examples, and both methods agree on every line. Look at the line n = 1: true: the loop never runs, because 1 % 3 is 1, and 1 is already the answer. The line n = 243: true shows the number the logarithm test got wrong, and dividing gets it right.

On the line n = -27: false (no loop: false), both methods are saved by their check for numbers below 1. The line for 1,162,261,467 takes 19 passes of the loop to reach 1. The value Integer.MAX_VALUE leaves remainder 1 at the first test, so the loop does not run, and Integer.MIN_VALUE never gets past the first check.

Complexity

The cost depends on how many threes the loop can take out of n.

  • Time: O(log n), because every pass divides n by 3, so after about log3 n passes no 3 can remain; for an int that is at most the 19 passes 319 needs.
  • Space: O(1), because the method only changes its own copy of n and keeps nothing else.

The no-loop test does one comparison and one remainder with a fixed number, so it takes O(1) time and space. Powers of four can also be checked with bit operations: see Power of Four.