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
Output: 12
Example 2
Output: 1
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:
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 inti2i3i5
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:
| Round | Candidates ×2, ×3, ×5 | Chosen | Pointers moved |
|---|---|---|---|
| 1 | 2, 3, 5 | 2 | ×2 |
| 2 | 4, 3, 5 | 3 | ×3 |
| 3 | 4, 6, 5 | 4 | ×2 |
| 4 | 6, 6, 5 | 5 | ×5 |
| 5 | 6, 6, 10 | 6 | ×2 and ×3 (tie) |
| 6 | 8, 9, 10 | 8 | ×2 |
| 7 | 10, 9, 10 | 9 | ×3 |
| 8 | 10, 12, 10 | 10 | ×2 and ×5 (tie) |
| 9 | 12, 12, 15 | 12 | ×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 intlongintlong
Java Solution
The method nthUglyNumber
- First, create the array
with room for n numbers, and put 1 inugly .ugly[0] - Set the three pointers
,i2 andi3 to 0, so all three start on the 1.i5 - A loop fills the entries from
up tok = 1 . In each round, compute the three candidatesn - 1 ,next2 andnext3 from the entries the pointers are on.next5 - Take the smallest of them with two calls to
, call itMath.min , and store it innext .ugly[k] - Move each pointer whose candidate equals
, using three separatenext statements, so a tie moves every pointer that made the value.if - When the loop ends, return
, the nth ugly number.ugly[n - 1]
The main
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:
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
The three separate ifelse if
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
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.ugly
Checking whether one given number is ugly is