Ugly Number

Decide whether a number has no prime factors other than 2, 3 and 5.

Call a positive whole number ugly when the only primes that divide it are 2, 3 and 5. Given an integer n, return true if it is ugly and false otherwise. The number 1 counts as ugly, and zero and negative numbers never do.

Example 1
Input: n = 6
Output: true
Explanation: 6 = 2 × 3.
Example 2
Input: n = 14
Output: false
Explanation: 14 = 2 × 7, and 7 is not allowed.
Example 3
Input: n = 1
Output: true
Solution

The Idea

Take the number 60 and keep splitting it into smaller pieces that multiply back to it. 60 is 2 × 30, and 30 is 2 × 15, and 15 is 3 × 5. So 60 = 2 × 2 × 3 × 5. None of 2, 3 and 5 can be split again, since only 1 and the number itself divide them. Such numbers are called primes, and 2, 2, 3 and 5 are the prime factors of 60.

All the prime factors of 60 are 2, 3 or 5, so 60 is ugly. Example 2 splits the same way into 14 = 2 × 7, and 7 is a prime outside the allowed three, so 14 is not ugly. Example 3, the number 1, has no prime factors at all, so nothing in it breaks the rule.

That raises the question: do we have to find every prime factor of n? For a large number that means trying a lot of divisors. Yet only three primes matter here, and every other prime is simply not allowed.

So take those three out and see what remains. In the picture, each arrow divides by one allowed prime, and the coloured box at the end of a row is what remains.

Dividing out 2, 3 and 5. 60 divided by 2 is 30, by 2 again is 15, by 3 is 5, by 5 is 1, so 60 is ugly. 14 divided by 2 is 7, and none of 2, 3 and 5 divides 7, so 7 is left and 14 is not ugly.

The row labelled n = 60 divides by 2 twice, then by 3, then by 5, and ends in the teal box at 1. The row labelled n = 14 divides by 2 once and reaches 7. Neither 2, 3 nor 5 divides 7, so the row stops in the orange box at 7.

What remains is n with every 2, 3 and 5 taken out. If it is 1, those three primes made up all of n. If it is bigger than 1, some other prime is hiding in it, like the 7 in 14, and the number is not ugly.

Solution Approach

Three choices shape the code: how to take out the allowed primes instead of factoring n fully, what the number left over tells us, and which inputs to turn away before any division.

Taking out 2, 3 and 5

Why not list all the prime factors of n and check each one? Finding them means trying divisors 2, 3, 4, 5 and so on, up to the square root of n. For Integer.MAX_VALUE, the largest int, that is over 46,000 tries, and the answer only depends on three primes.

Instead, divide by 2 for as long as the remainder is 0, then do the same with 3, then with 5. The order does not change what remains: starting with 5, 60 becomes 12, the 2s turn 12 into 3, and the 3 turns that into 1, the same end as in the picture.

Reading what is left

Once no 2, 3 or 5 divides it any more, is the remaining number enough to decide? Yes. Every allowed prime has been taken out as often as it appeared, so the remaining number is exactly the product of the other primes. That product is 1 when there are none, and at least 7 when there is one.

Zero, negative numbers and overflow

What happens with 0? Its remainder after dividing by 2 is 0, and 0 / 2 is 0 again, so dividing out the 2s would never finish. Ugly numbers are positive anyway, so the method returns false for any n that is 0 or less, before the first division.

Can the arithmetic go past the range of an int? The method only divides, and dividing by 2, 3 or 5 always moves n closer to 0. Every value it holds lies between 1 and the input, so even Integer.MAX_VALUE needs no long.

Java Solution

The method isUgly works in these steps:

  1. First, return false when n is 0 or less, since ugly numbers are positive and 0 would never stop dividing.
  2. Put the allowed primes in a small array, allowed = {2, 3, 5}, and loop over it, with p taking each prime in turn.
  3. Inside, a while loop divides n by p as long as n % p == 0, that is, as long as p divides n with no remainder.
  4. After all three primes, return n == 1: true when nothing but 2, 3 and 5 was in n.

The main method runs the three examples, 60 from the picture, 49 (which is 7 × 7), then 0, -6, 230, Integer.MAX_VALUE and Integer.MIN_VALUE.

Java
public class UglyNumber {

    public static boolean isUgly(int n) {
        if (n <= 0) {
            return false;                     // ugly numbers are positive; also stops 0
        }
        int[] allowed = {2, 3, 5};
        for (int p : allowed) {
            while (n % p == 0) {
                n /= p;                       // take out one factor p
            }
        }
        return n == 1;                        // anything else has another prime factor
    }

    public static void main(String[] args) {
        int[] tests = {6, 14, 1, 60, 49, 0, -6, 1 << 30, Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int n : tests) {
            System.out.println("isUgly(" + n + ") = " + isUgly(n));
        }
    }
}

Running it prints:

Output
isUgly(6) = true
isUgly(14) = false
isUgly(1) = true
isUgly(60) = true
isUgly(49) = false
isUgly(0) = false
isUgly(-6) = false
isUgly(1073741824) = true
isUgly(2147483647) = false
isUgly(-2147483648) = false

Look at isUgly(49) = false. No 2, 3 or 5 divides 49, so not a single division happens and 49 itself is what remains. The line isUgly(1073741824) = true is 230: the loop for p = 2 divides it thirty times and reaches 1.

Next comes isUgly(2147483647) = false, for Integer.MAX_VALUE. None of 2, 3 and 5 divides 2,147,483,647, so it remains whole and the answer is false. The last line, for Integer.MIN_VALUE, and the lines for 0 and -6 all come from the first check, before any division.

That first check matters most for 0. A copy of the method without it never returned from isUgly(0): the run printed nothing for that call and had to be stopped after 10 seconds.

Complexity

The cost is the number of divisions, plus at most one failed remainder check for each of the three primes.

  • Time: O(log n), because every division at least halves n, so a positive int takes at most 30 divisions to reach 1, the count that 230 needs.
  • Space: O(1), because the method changes n itself and keeps only the three-element allowed array, whatever the size of n.

Listing the ugly numbers in increasing order is a different task, solved in Nth Ugly Number.