# Count pairs with sum as a prime number and less than n in C++

C++Server Side ProgrammingProgramming

We are given a positive number n as input. The goal is to find the count of possible pairs (i,j) such that each pair has sum (i+j) which is prime and is less than n. Also i != j and i,j>=1 If n is 4 then only 1 pair is possible which is (1,2). Here 1+2 = 3 is prime and less than 4. Also 1,2 >=1.

Let us understand with examples.

Input − n=7

Output − Count of pairs with sum as a prime number and less than n are − 3

Explanation − Pairs will be (1,2), (1,4), (2,3). Sum 3, 5, 5 are prime and less than 7.

Input − n=10

Output − Count of pairs with sum as a prime number and less than n are − 6

Explanation

Pairs will be (1,2), (1,4), (2,3), (1,6), (2,5), (3,4).

Sum 3, 5, 5, 7, 7, 7 are prime and less than 10.

## Approach used in the below program is as follows

In this approach we will first find all prime numbers less than n using Sieve of Sundaram in function check_prime(bool check[], int temp).

Also for each odd number temp, the count of distinct pairs that have sum temp will be temp/2.

Except 2 all prime numbers are odd so if we find any prime number less than n then we will add temp/2 to count of pairs.

• Take variable n as input.

• Function prime_pair(int n) takes n and returns the count of pairs with sum as a prime number and less than n.

• Take the initial count as 0.

• As Sieve of Sundaram generates prime numbers less than 2*n+2 for input n. We reduce n to its half and store in temp_2.

• Create an array Check[] of length temp_2 to mark all numbers of the form ( i+j+2*i*j ) as True. Initialize it with all elements as false.

• Using function check_prime(bool check[], int temp), initialize check[] with true for numbers of the form (i+j+2*i*j). And this sum < temp.

• Now traverse Check[] using for loop from index i=0 to i<temp_2.

• For each check[i] as false, prime number will be temp=2*i+1.

• Pairs that add up to temp will be temp/2.

• At the end of the for loop we will have total pairs with sum as prime and less than n.

• Return count as result.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void check_prime(bool check[], int temp){
for (int i=1; i<=temp; i++){
for (int j=i; (i + j + 2*i*j) <= temp; j++){
check[i + j + 2*i*j] = true;
}
}
}
int prime_pair(int n){
int count = 0;
int temp;
int temp_2 = (n-2)/2;
bool check[temp_2 + 1];
memset(check, false, sizeof(check));
check_prime(check, temp_2);
for (int i=1; i <= temp_2; i++){
if (check[i] == false){
temp = 2*i + 1;
count += (temp / 2);
}
}
return count;
}
int main(){
int n = 10;
cout<<"Count of pairs with sum as a prime number and less than n are: " <<prime_pair(n);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of pairs with sum as a prime number and less than n are: 6
Published on 02-Dec-2020 12:41:23