For this problem, we can use a simple for-loop to generate values of a and b.Set a=i and b=2n−i. Loop it through the integers from 2 to 2n. Check if they are both prime and that 2n is equal to a+b. Recall that an integer is prime if it is greater than 1 and cannot be formed by multiplying two smaller natural numbers.
Loop i from 2 to sqrt(n)
Exclude even numbers.
#include <iostream> #include <cmath> using namespace std; bool isprime(int n){ if(n < 2){ return false; } if(n==2){ return true; } if(n%2 == 0){ return false; } int top = sqrt(n) +1; for(int i = 3; i <= top; i+=2){ if(n%i == 0){ return false; } } return true; } void getPrimeAverage(int N){ for(int i = 2; i <=N; i++){ if(isprime(i)){ if(isprime(2*N -i)){ cout<<i<<" "<<(2*N-i)<<endl; return; } } } return; } int main() { int T; cin >> T; for(int i = 0; i < T; i++){ int N; cin >> N; getPrimeAverage(N); } return 0; }
Comments