Roy and Shopping

Alfi asked Roy to go for shopping with her. Witty Roy came up with a condition. He said, for each product of MRP (Maximum Retail Price) R, she'll have to pay minimum of all the prime factors of R and he himself will pay rest of the amount. Without giving it a second thought Alfi agreed.

Example:

Input:  r = 10
Output: 8

Approach

C++

#include <bits/stdc++.h>
using namespace std;
#define MAXN 1000001
int spf[MAXN];
void sieve()
{
    spf[1] = 1;
    for (int i = 2i < MAXN; i++)
        spf[i] = i;
    for (int i = 4i < MAXN; i += 2)
        spf[i] = 2;

    for (int i = 3i * i < MAXN; i++)
    {
        if (spf[i] == i)
        {
            for (int j = i * ij < MAXN; j += i)
                if (spf[j] == j)
                    spf[j] = i;
        }
    }
}
vector<intgetFactorization(int x)
{
    vector<intret;
    while (x != 1)
    {
        ret.push_back(spf[x]);
        x = x / spf[x];
    }
    return ret;
}
int main()
{

    sieve();

    int r = 10;
    vector<intres = getFactorization(r);
    cout << r - res[0] << "\n";
}


No comments:

Post a Comment