Problem 239
Nth Ugly Number
Medium · 20 pts · Math, Dynamic Programming, Heap
Problem
An ugly number is a positive integer whose only prime factors are 2, 3 and 5. The number 1 also counts as ugly, so the sequence begins 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, ... (7 and 11 are missing because they are primes other than 2, 3 and 5). Print the N-th ugly number. Build the sequence in increasing order. Every ugly number after 1 is 2, 3 or 5 times an earlier one, so keep three pointers into the sequence and repeatedly append the smallest of 2 × u[i2], 3 × u[i3] and 5 × u[i5], advancing every pointer that produced it to avoid duplicates.
Input
A single integer N.
Output
Print the N-th ugly number.
Constraints
1 <= N <= 1690
Example input
10
Example output
12
Explanation
The ugly numbers in order are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12. The 10th is 12.