Shweta , Riddhima and Chocolates - A

Shweta Patel and Riddhima Yadav are two very cool-minded girls. They have a very special quality to calm themselves and stay happy even in most adverse situations. But when it comes to chocolates, both of them become extremely violent.

Once they both went to a shop to buy chocolates but the shopkeeper told them that he has only 'S' number of chocolates. So Shweta and Riddhima bought all the 'S' chocolates and decided to distribute the chocolates between them such that Shweta gets p chocolates and Riddhima gets q chocolates with the condition that both p and q are prime numbers and the difference between them is minimum.

Since both the girls are busy chatting on Facebook. So they asked you to help them find the value of p and q. If multiple pairs of p and q exist then print the pair having minimum p such that p is always less than equal to q.

Example:

Input:  12512
Output: 6211 6301

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool isprime(long long n)
{
    if (n <= 1)
        return false;
    for (long long i = 2i <= sqrt(n); i++)
        if (n % i == 0)
            return false;
    return true;
}
int main()
{
    long long s = 12512;
    long long a = s / 2 - 1;
    long long b = s / 2 + 1;
    while (true)
    {
        if (isprime(a) && isprime(b))
            break;
        else
        {
            a--;
            b++;
        }
    }
    cout << a << " " << b << "\n";
}


No comments:

Post a Comment