313 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.
bool existsInPrimeList(vector<int> &primes, int n) {
    for (int i = 0; i < primes.size(); i++) {
        if (n == primes.at(i)) return true;
    }
    return false;
}

// primes: all numbers the evenly divide n except for 1 and itself
vector<int> generatePrimeFactors(int n) {
    vector<int> primes;
    int z = 2;
    for (int i = 2; i < n; i++) {
        // evenly divides
        if (n % i == 0) {
            primes.push_back(i);
            i = 2;
            n /= i;

            for (int j = 2; j <= n; i++) {
                if (n % j == 0) {
                    primes.push_back(j);
                    j = 2;
                    n /= j;
                }
            }
            break;
        }
    }
    return primes;
}

int nthSuperUglyNumber(int n, vector<int>& primes) {
    if (n == 1) { return 1; }
    // all prime factors are from the prime list
    vector<int> factors;
    int count = 1;
    int current_n = 2;
    bool exists;

    while (count + 1 < n) {
        exists = true;
        factors = generatePrimeFactors(current_n);
        // make sure factors are all from the prime list
        for (auto i : factors) {
            if (!existsInPrimeList(primes, i)) {
                exists = false;
                break;
            }
        }
        if (exists) {
            count++;
        }

        current_n++;
        factors.empty();
    }

    return current_n + 1;
}

int main()
{
    //vector<int> test = { 2,3,5 };
    //cout << nthSuperUglyNumber(1, test) << endl;

    //test = { 2 };
    //cout << nthSuperUglyNumber(3, test) << endl;

    vector<int> test = { 2,3,5 };
    cout << nthSuperUglyNumber(50, test) << endl;
}

Last updated