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.
找到第n个丑陋数。
所有的丑陋数都是从1开始乘2,3,5得到的,所以我们在已生成的数中找到乘以2,3,5之后比所有已生成数大的中最小的那个就是下一个数。
我们要怎么找这个数呢,把所有已生成数存在数组里,第一个数是1。
我们要找的下一个数一定是:
min(results[i] * 2, results[j] * 3, results[k] * 5)
这里的i,j,k怎么确定?
如果最后一个丑陋数是使用i*2生成的,那么下一次一定就不用找i了。所以:
var nthUglyNumber = function(n) {
var results = [1];
var i = 0, j = 0, k = 0;
while (results.length < n)
{
results.push(Math.min(results[i] * 2, results[j] * 3, results[k] * 5));
if (results[results.length - 1] === results[i] * 2) ++i;
if (results[results.length - 1] === results[j] * 3) ++j;
if (results[results.length - 1] === results[k] * 5) ++k;
}
return results.pop();
};
Super Ugly Number
Write a program to find the nth super ugly number.
Super ugly numbers are positive numbers whose all prime factors are in the given prime list primes of size k.
For example, [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] is the sequence of the first 12 super ugly numbers given primes = [2, 7, 13, 19] of size 4.
Note:
(1) 1 is a super ugly number for any given primes.
(2) The given numbers in primes are in ascending order.
(3) 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
这题和上题差不多,只不过质数不是固定的,是参数给出的,那么使用和刚才一样的思想:
var nthSuperUglyNumber = function(n, primes) {
var num = primes.length;
var indexs = [];
for (var i = 0;i<num;i++)
indexs.push(0);
var result = [1];
for (n;n>1;n--) {
var min = Number.MAX_VALUE;
for (var j = 0;j < num;j++) {
if (result[indexs[j]] * primes[j] < min) {
min = result[indexs[j]] * primes[j];
}
}
for (j = 0;j < num;j++) {
if (result[indexs[j]] * primes[j] == min) {
indexs[j]++;
}
}
result.push(min);
}
return result.pop();
};