Ugly Number II
Problem
An ugly number is a positive integer whose prime factors are limited to 2
, 3
, and 5
.
Given an integer n
, return the nth
ugly number.
Example 1:
Input: n = 10 Output: 12 Explanation: [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
Example 2:
Input: n = 1 Output: 1 Explanation: 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
Constraints:
1 <= n <= 1690
Solution
/**
* @param {number} n
* @return {number}
*/
var nthUglyNumber = function(n) {
let nums = [1];
let index2 = 0;
let index3 = 0;
let index5 = 0;
for (let i = 1; i < n; ++i) {
let min = Math.min(2 * nums[index2], 3 * nums[index3], 5 * nums[index5]);
nums.push(min);
if (min === 2 * nums[index2]) index2++;
if (min === 3 * nums[index3]) index3++;
if (min === 5 * nums[index5]) index5++;
}
return nums[n - 1];
};
The next ugly number in a sequence must be a previous ugly number multiplied by either 2
, 3
, or 5
. Thus, start with an array nums
containing only the value 1, and keep track of the index of each prime factor. The next number in the sequence must be the smallest value of the three factors multiplied by nums[index]
. Next, increment the index of that factor by 1
, and repeat this process until nums
contains n
values.