Ugly Number
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
class Solution {
public:
bool isUgly(int num) {
if(num <= 0) return false;
while(num % 2 == 0){
num /= 2;
}
while(num % 3 == 0){
num /= 3;
}
while(num % 5 == 0){
num /= 5;
}
return num == 1;
}
};
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.
class Solution {
public:
int nthUglyNumber(int n) {
int *res = new int[n];
res[0] = 1;
int iter2 = 0;
int iter3 = 0;
int iter5 = 0;
for(int i = 1; i < n; i++){
int temp = std::min(*(res + iter2) * 2, std::min(*(res + iter3) * 3, *(res + iter5) * 5));
if(temp == *(res + iter2) * 2)
iter2++;
if(temp == *(res + iter3) * 3)
iter3++;
if(temp == *(res + iter5) * 5)
iter5++;
*(res + i) = temp;
}
int temp = res[n - 1];
delete res;
return temp;
}
};
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.
class Solution {
public:
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> iters(primes.size(), 0);
vector<int> uglys(n , INT_MAX);
uglys[0] = 1;
for(int i = 1; i < n; i++){
for(int j = 0; j < primes.size(); j++){
uglys[i] = min(uglys[i], primes[j]*uglys[iters[j]]);
}
for(int k = 0; k < primes.size(); k++){
if(uglys[i] == primes[k]*uglys[iters[k]])
iters[k]++;
}
}
return uglys[n - 1];
}
};