一.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
.
Note that 1
is typically treated as an ugly number.
class Solution {
public:
bool isUgly(int num) {
if(num<=)return false;
while(num%==){
num /= ;
}
while(num%==){
num /= ;
}
while(num%==){
num /= ;
}
return num== ? true:false;
}
};
二.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 index2=,index3=,index5=;
int ugly2=,ugly3=,ugly5=;
vector<int> res(n,);
int index = ;
while(index < n){
while(res[index2]* <= res[index-]){
index2++;
}
while(res[index3]* <= res[index-]){
index3++;
}
while(res[index5]* <= res[index-]){
index5++;
}
ugly2 = res[index2]*;
ugly3 = res[index3]*;
ugly5 = res[index5]*;
res[index++] = min(ugly2,min(ugly3,ugly5));
}
return res[n-];
}
};
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) {
int primes_size = primes.size();
vector<int> vec_indexs(primes_size,) ,vec_uglys(n,) ;
for(int i=;i<n;++i){
int min_ugly = INT_MAX;
for(int j=;j<primes_size;++j){
int index = vec_indexs[j];
while(primes[j]*vec_uglys[index] <= vec_uglys[i-]){
index++;
}
min_ugly = min(min_ugly,primes[j]*vec_uglys[index]);
vec_indexs[j] = index;
}
vec_uglys[i] = min_ugly;
}
return vec_uglys.back();
}
};