Ugly number is a number that only have factors 3
, 5
and 7
.
Design an algorithm to find the Kth ugly number. The first 5 ugly numbers are 3, 5, 7, 9, 15 ...
Example
If K=4
, return 9
.
Challenge
O(K log K) or O(K) time.
class Solution {
public:
/*
* @param k: The number k.
* @return: The kth prime number as description.
*/
long long kthPrimeNumber(int k) {
// write your code here
vector<long long> primeList(k+1);
primeList[0] = 1;
int nextPrimeIdx = 1;
long long i3 = 0;
long long i5 = 0;
long long i7 = 0;
long long nextPrimeVal;
while (nextPrimeIdx <= k)
{
nextPrimeVal = min(min(primeList[i3]*3, primeList[i5]*5), primeList[i7]*7);
primeList[nextPrimeIdx] = nextPrimeVal;
while (primeList[i3]*3 <= nextPrimeVal)
i3++;
while (primeList[i5]*5 <= nextPrimeVal)
i5++;
while (primeList[i7]*7 <= nextPrimeVal)
i7++;
nextPrimeIdx++;
}
return primeList[k];
}
};