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 < 1) return false;
while((num & 1) == 0) num >>= 1;
while(num % 3 == 0) num /= 3;
while(num % 5 == 0) num /= 5;
return num == 1;
}
};
这里去掉括号竟然会WA,难道 == 的优先级要高于 & ?
while((num & 1) == 0) num >>= 1;
Ugly Number II
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.
Example:
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.
Note:
- 1 is typically treated as an ugly number.
- n does not exceed 1690.
《剑指offer》上也有丑数这道题。
class Solution {
public:
int nthUglyNumber(int n) {
vector<int> v(1700, 1); // 这里得写常数
v[1] = 2;
v[2] = 3;
v[3] = 4;
v[4] = 5;
int p2 = 0, p3 = 0, p5 = 0;
for(int i = 4; i < n-1; ++i){
while(v[p2]*2 <= v[i]) ++p2;
while(v[p3]*3 <= v[i]) ++p3;
while(v[p5]*5 <= v[i]) ++p5;
v[i+1] = min(min(v[p2]*2, v[p3]*3), v[p5]*5);
} return v[n-1];
}
};
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.
Example:
Input: n = 12, primes = [2,7,13,19]
Output: 32
Explanation: [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 is a super ugly number for any given primes.
- The given numbers in primes are in ascending order.
- 0 < k ≤ 100, 0 < n ≤ 106, 0 < primes[i] < 1000.
- The nth super ugly number is guaranteed to fit in a 32-bit signed integer.
下面这份代码的时间复杂度为 O(nklogk)
… 明显还可以优化
class Solution {
public:
Solution(){
v[0] = 1;
}
int nthSuperUglyNumber(int n, vector<int>& primes) {
vector<int> pv(primes.size(), 0);
set<int> s;
for(int i = 0, e = n-1; i < e; ++i){
for(int j = 0; j < primes.size(); ++j){
while(v[pv[j]]*primes[j] <= v[i]) ++pv[j];
s.insert(v[pv[j]]*primes[j]);
} v[i+1] = *(s.begin());
s.erase(s.begin());
} return v[n-1];
}
private:
int v[1000000];
};