264 Ugly Number II
Last updated
Last updated
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number, and n does not exceed 1690.
The Idea: Preprocess first to produce all the possible ugly numbers. The visualization below shows us how this is done. Powers here allow us to represent number of times the prime factor is used. For example, 2^2 and 3^4 make up 22333*3 (a combination that we care about and produces a unique number). Then simply index this array to return the nth ugly number.
Complexity: O(1) after preprocessing, O(1) space assuming constant bound of INT_MAX