1. 程式人生 > >[CareerCup] 7.7 The Number with Only Prime Factors 只有質數因子的數字

[CareerCup] 7.7 The Number with Only Prime Factors 只有質數因子的數字

7.7 Design an algorithm to find the kth number such that the only prime factors are 3,5, and 7.

這道題跟之前LeetCode的那道Ugly Number II 醜陋數之二基本沒有啥區別,具體講解可參見那篇,程式碼如下:

class Solution {
public:
    int getKthMagicNumber(int k) {
        vector<int> res(1, 1);
        int i3 = 0, i5 = 0, i7 = 0;
        
while (res.size() < k) { int m3 = res[i3] * 3, m5 = res[i5] * 5, m7 = res[i7] * 7; int mn = min(m3, min(m5, m7)); if (mn == m3) ++i3; if (mn == m5) ++i5; if (mn == m7) ++i7; res.push_back(mn); } return
res.back(); } };