Sum of Prime
Problem Statement: Given a number (greater than 2), print two prime numbers whose sum will be equal to given number, else print -1 if no such number exists.
NOTE: A solution will always exist if the number is even.
If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, and a < c then print [a, b] only
and not all possible solutions.
Input:
The first line contains an integer T, depicting total number of test cases. Then following T lines contains an integer N.
Output:
Print the two prime numbers in a single line with space in between.
Constraints:
1 ≤ T ≤ 50
2 ≤ N ≤ 1000000
Example:
Input:
2
8
3
Output
3 5
-1
Explanation:
Testcase 1: two prime numbers from 1 to 8 are 3 and 5 whose sum is 8.
This problem is available in Geeksforgeeks, the link of which is mentioned below.
https://practice.geeksforgeeks.org/problems/sum-of-prime/0
Solution:
CPP Solution
#include<iostream>
using namespace std;
//Function to determine whether a number is prime or not
bool isprime(int n)
{
if(n<=1)
{
return false;
}
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
{
return false;
}
}
return true;
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int flag=0;
for(int i=1;i<n;i++)
{
if(isprime(i)==true && isprime(n-i)==true)
{
cout<<i<<" "<<n-i<<endl;
flag=1;
break;
}
}
if(flag==0)
{
cout<<-1<<endl;
}
}
return 0;
}
*Please comment if you have any confusion in this solution*
Is the time complexity is O(n^(3/2))
ReplyDeleteYes
Deletevery good.
ReplyDeleteare you interested for doing a job of software engineer at backend.
i have an opportunity.
Sure, please provide your mail id. My id is gogolgd96@gmail.com
DeleteGood job 👍
ReplyDeleteGreat
ReplyDelete