Nth Ugly Number

Find the nth positive number whose only prime factors are 2, 3 and 5.

An ugly number is a positive integer whose only prime factors, the primes that multiply together to give it, are 2, 3 and 5. The number 1 counts as ugly too, so the sequence starts 1, 2, 3, 4, 5, 6, 8, 9, 10, 12. Given an integer n between 1 and 1690, return the nth ugly number.

Example 1
Input: n = 10
Output: 12
Example 2
Input: n = 1
Output: 1
Solution

The Idea

Take a number and split it into a product of primes, numbers such as 2, 3, 5 and 7 that cannot be split any further. The number 12 splits into 2 × 2 × 3, so its prime factors are 2 and 3, and 12 is ugly. But 14 splits into 2 × 7, and the 7 makes it not ugly. The number 1 has no prime factors at all, so nothing other than 2, 3 and 5 gets in, and it is the first ugly number.

Now count 1, 2, 3 and onwards, keeping only the ugly numbers. The number 7 is dropped, being a prime other than 2, 3 and 5, and so is 11. The tenth number kept is 12, the answer to Example 1. Further on, the gaps grow: the 1690th ugly number is already 2,123,366,400. Can we reach the ugly numbers without stepping over every other number on the way?

Look at how the ugly numbers are made: 12 is 6 × 2, 10 is 5 × 2, and 9 is 3 × 3. Take away one factor of 2, 3 or 5 from an ugly number above 1, and what is left is a smaller ugly number. So the list can be built from itself: the next ugly number is the smallest product of an earlier entry and 2, 3 or 5 that is not in the list yet.

To find that product without trying every entry, keep three pointers, markers that each sit on one entry of the list, one per factor. The ×2 pointer sits on the earliest entry whose double is not in the list yet. The ×3 and ×5 pointers do the same for times 3 and times 5. The picture shows the list once it holds five numbers, with the sixth ugly number next:

The list so far is 1, 2, 3, 4, 5. The ×2 pointer is on 3, the ×3 and ×5 pointers are on 2. The three candidates are 3 × 2 = 6, 2 × 3 = 6 and 2 × 5 = 10. The smallest, 6, becomes the next ugly number, and the ×2 and ×3 pointers both move on.

In the picture, the ×2 pointer is on 3, because the doubles of 1 and 2, which are 2 and 4, are already in the list. The ×3 and ×5 pointers are both on 2, since 3 and 5 are in the list too. The row labelled "the three candidates" holds their products: 3 × 2 = 6, 2 × 3 = 6 and 2 × 5 = 10. The smallest, 6, fills the ? cell.

Two of the candidates were 6. If only the ×2 pointer moved on, the ×3 pointer would offer 6 again in the next round, and 6 would enter the list twice. So every pointer whose candidate was chosen moves on, here both the ×2 and the ×3 pointer. Each round then adds one new ugly number, and the list stays in increasing order.

Solution Approach

Besides the slow way of testing each integer, four decisions shape the code: where the ugly numbers are kept, how the pointers move, what happens on a tie, and how the products stay inside an int.

Testing each integer

What would the plain approach look like? Take each integer in turn, divide out 2 as long as it divides evenly, then 3, then 5, and see whether 1 is left. For example, 12 becomes 6, then 3, then 1, so it is ugly, while 14 stops at 7. This works, but to reach the 1690th ugly number it tests all 2,123,366,400 integers up to it, and only 1690 of them pass.

Keeping the list in an array

Where do the ugly numbers live? Since n is known from the start, an int array of n entries is enough. Entry 0 holds 1, and each round fills the next entry. The ×2, ×3 and ×5 pointers become three indexes into this array, named i2, i3 and i5, and all three start at 0, the entry holding 1.

Moving the pointers forward

Could a pointer skip an ugly number? Take 12, which is 6 × 2. The ×2 pointer leaves an entry only after that entry's double has gone into the list, so it waits on 6 until 12 is chosen. Every ugly number above 1 is protected the same way, through the factor it was made with.

Why is it enough to move forward? The list grows in increasing order, so the entries after a pointer give bigger products than the entry it is on. A pointer never needs to look back, and it moves at most one place per round.

Ties between candidates

How often do candidates tie? They tie whenever a number can be made in two ways. The table follows the nine rounds that build Example 1's list, naming each pointer by its factor:

RoundCandidates ×2, ×3, ×5ChosenPointers moved
12, 3, 52×2
24, 3, 53×3
34, 6, 54×2
46, 6, 55×5
56, 6, 106×2 and ×3 (tie)
68, 9, 108×2
710, 9, 109×3
810, 12, 1010×2 and ×5 (tie)
912, 12, 1512×2 and ×3 (tie)

Rounds 5, 8 and 9 are ties. Here 6 is 3 × 2 and 2 × 3, 10 is 5 × 2 and 2 × 5, and 12 is 6 × 2 and 4 × 3. In each of them both pointers move, and the list ends as [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] with no value twice. Its tenth entry, 12, answers Example 1.

Staying inside an int

Can a product grow too big? A Java int tops out at 2,147,483,647. With n at most 1690, the answer is 2,123,366,400, and redoing every product as a long shows that no candidate goes above it, so plain int products are safe. Two places further, the 1692nd ugly number is 2,147,483,648, which no longer fits. For n above 1691, the array and the products would have to be long.

Java Solution

The method nthUglyNumber works in these steps:

  1. First, create the array ugly with room for n numbers, and put 1 in ugly[0].
  2. Set the three pointers i2, i3 and i5 to 0, so all three start on the 1.
  3. A loop fills the entries from k = 1 up to n - 1. In each round, compute the three candidates next2, next3 and next5 from the entries the pointers are on.
  4. Take the smallest of them with two calls to Math.min, call it next, and store it in ugly[k].
  5. Move each pointer whose candidate equals next, using three separate if statements, so a tie moves every pointer that made the value.
  6. When the loop ends, return ugly[n - 1], the nth ugly number.

The main method runs both examples, prints the first 15 ugly numbers, then asks for n = 1690, the largest allowed, and for n = 1692, two places past it.

Java
import java.util.Arrays;

public class NthUglyNumber {

    public static int nthUglyNumber(int n) {
        int[] ugly = new int[n];
        ugly[0] = 1;
        int i2 = 0, i3 = 0, i5 = 0;   // the next ugly number to multiply by 2, 3 and 5
        for (int k = 1; k < n; k++) {
            int next2 = ugly[i2] * 2;
            int next3 = ugly[i3] * 3;
            int next5 = ugly[i5] * 5;
            int next = Math.min(next2, Math.min(next3, next5));
            ugly[k] = next;
            if (next == next2) i2++;  // three separate ifs: on a tie such as 6,
            if (next == next3) i3++;  // every pointer that made it moves on,
            if (next == next5) i5++;  // so 6 is stored once
        }
        return ugly[n - 1];
    }

    public static void main(String[] args) {
        System.out.println(nthUglyNumber(10));
        System.out.println(nthUglyNumber(1));
        int[] first15 = new int[15];
        for (int n = 1; n <= 15; n++) {
            first15[n - 1] = nthUglyNumber(n);
        }
        System.out.println(Arrays.toString(first15));
        System.out.println(nthUglyNumber(1690));
        System.out.println(nthUglyNumber(1692));   // past the limit: int overflows
    }
}

Running it prints:

Output
12
1
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
2123366400
-2147483648

The 12 and the 1 at the top answer Example 1 and Example 2. The list on the third line carries on past 12 with 15, 16, 18, 20 and 24, and leaves out numbers such as 14 = 2 × 7 and 21 = 3 × 7.

The fourth line, 2123366400, is the 1690th ugly number, still below the int limit. The last line shows what happens past the limit. The 1692nd ugly number is 2,147,483,648, made as 1,073,741,824 × 2, and that product wraps around to -2147483648, a negative number the method then returns.

The three separate if statements matter. With else if instead, a tie moves only one pointer, and a run of that version for n = 10 builds [1, 2, 3, 4, 5, 6, 6, 8, 9, 10], returning 10 instead of 12.

Complexity

Each round of the loop adds one ugly number to the array, and the array keeps all of them until the end.

  • Time: O(n), because the loop runs n - 1 rounds, and each round computes three products, takes a minimum and moves at most three pointers.
  • Space: O(n), because the ugly array holds all n numbers, and a pointer may still need an early entry: in round 9 of Example 1 the ×5 pointer is still on 3.

Checking whether one given number is ugly is Ugly Number.