Write a program to find the nth ugly number.
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
n?
n is a positive integer and can be as large as 1690.nth ugly number as an integer?
nth ugly number.To find the nth ugly number, we can use a dynamic programming approach combined with a min-heap (priority queue).
1 along with its multiples by 2, 3, and 5.current_number * 2, current_number * 3, current_number * 5) and insert them back into the heap if they are not already present.nth ugly number.nth number when the count matches n.#include <iostream>
#include <vector>
#include <queue>
#include <unordered_set>
int nthUglyNumber(int n) {
if (n <= 0) return 0; // Assuming we handle invalid inputs with a default return value.
std::priority_queue<long, std::vector<long>, std::greater<long>> minHeap;
std::unordered_set<long> seen; // To avoid duplicates
// Initialize with the first ugly number
minHeap.push(1);
seen.insert(1);
long currentUgly = 1;
// Factors for computing ugly numbers
std::vector<int> factors = {2, 3, 5};
// We need to find the nth ugly number
for (int i = 1; i <= n; ++i) {
currentUgly = minHeap.top();
minHeap.pop();
for (int factor : factors) {
long newUgly = currentUgly * factor;
if (seen.find(newUgly) == seen.end()) {
minHeap.push(newUgly);
seen.insert(newUgly);
}
}
}
return static_cast<int>(currentUgly);
}
int main() {
int n = 10; // Example usage
std::cout << "The " << n << "th ugly number is: " << nthUglyNumber(n) << std::endl;
return 0;
}
O(log k), where k is the size of the heap.n times, the overall complexity is O(n log n).nth ugly number:
O(n)Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?