# 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 2*2*3*3*3\*3 (a combination that we care about and produces a unique number). Then simply index this array to return the nth ugly number.

![](/files/-LoJInKAFd0Obx5SDG_p)

**Complexity:** O(1) after preprocessing, O(1) space assuming constant bound of `INT_MAX`

```cpp
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];
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/264-ugly-number-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
