Ugly Number II
Description
Write a program to find the n
-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5
.
Example:
Input: n = 10 Output: 12 Explanation:1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first10
ugly numbers.
Note:
1
is typically treated as an ugly number.n
does not exceed 1690.
Solution(javascript)
const nthUglyNumber = (n) => {
const result = [1]
let p1 = 0
let p2 = 0
let p3 = 0
while (result.length < n) {
const num1 = result[p1] * 2
const num2 = result[p2] * 3
const num3 = result[p3] * 5
const min = Math.min(num1, num2, num3)
if (num1 === min) {
p1 += 1
} else if (num2 === min) {
p2 += 1
} else {
p3 += 1
}
if (min !== result[result.length - 1]) {
result.push(min)
}
}
return result[n - 1]
}