Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
3,217 views
in Online Assessments by Expert (115,900 points) | 3,217 views

2 Answers

0 like 0 dislike
#include <bits/stdc++.h>

using namespace std;

vector<int> primes(int n, int count)

{

    vector<int> prime_list;

    if (n < 2)

        return prime_list;

    vector<int> seive(n + 1, 1);

    seive[0] = 0, seive[1] = 0;

    for (int num = 2; num <= n; num++)

    {

        if (seive[num] == 0)

            continue;

        for (int j = num * num; j <= n; j += num)

        {

            seive[j] = 0;

        }

    }

    for (int i = 2; i < n; i++)

    {

        if (count == 0)

            break;

        if (seive[i] == 1 && count > 0)

        {

            prime_list.push_back(i);

            count--;

        }

    }

 

    return prime_list;

}

int helper(int d, vector<int> &prime_list, vector<int> &dp)

{

    if (d == 0)

        return 0;

    if (d < 0)

        return INT_MAX;

    if (dp[d] != -1)

        return dp[d];

    int steps = INT_MAX;

    for (int i = 0; i < prime_list.size(); i++)

    {

        steps = min(steps, helper(d - prime_list[i], prime_list, dp));

    }

    if (steps == INT_MAX)

        dp[d] = INT_MAX;

    else

        dp[d] = steps + 1;

    return dp[d];

}

int main()

{

    int d, k;

    cin >> d >> k;

    vector<int> dp(d + 1, -1);

    vector<int> prime_list = primes(d, k);

    int ans = helper(d, prime_list, dp);

    if (ans == INT_MAX)

        cout << -1 << endl;

    else

        cout << ans << endl;

}
by (300 points)
0 like 1 dislike

Question asked : image 

by Expert (115,900 points)