264 Ugly Number II

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

int nthUglyNumber(int n) {
    static vector<int> ugly_numbers;
    ugly_numbers.reserve(1690 + 1);

    int i, j, k;
    long long a, b, c;
    if (ugly_numbers.empty()) {
        for (i = 0; pow(2, i) <= INT_MAX; i++) {
            for (j = 0; pow(3, j) * pow(2, i) <= INT_MAX; j++) {
                for (k = 0; pow(5, k) * pow(3, j) * pow(2, i) <= INT_MAX; k++) {
                    ugly_numbers.push_back(pow(2, i) * pow(3, j) * pow(5, k));
                }
            }
        }
        sort(ugly_numbers.begin(), ugly_numbers.end());
    }
    return ugly_numbers[n - 1];
}

Last updated