Count of pairs in an Array whose sum is Prime - GeeksforGeeks

17 May, 2021
Given an array arr of size N elements, the task is to count the number of pairs of elements in the array whose sum is prime.
Examples: 
Input: arr = {1, 2, 3, 4, 5} Output: 5 Explanation: Pairs with sum as a prime number are: {1, 2}, {1, 4}, {2, 3}, {2, 5} and {3, 4}
Input: arr = {10, 20, 30, 40} Output: 0 Explanation: No pair whose sum is a prime number exists.  
Naive Approach: Calculate the sum of every pair of elements in the array and check if that sum is a prime number or not.
Below code is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to count of pairs// of elements in an array// whose sum is prime#include <bits/stdc++.h>using namespace std; // Function to check whether a// number is prime or notbool isPrime(int num){    if (num == 0 || num == 1) {        return false;    }    for (int i = 2; i * i <= num; i++) {        if (num % i == 0) {            return false;        }    }    return true;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){    int count = 0;    for (int i = 0; i < n; i++) {        for (int j = i + 1; j < n; j++) {            int sum = arr[i] + arr[j];            if (isPrime(sum)) {                count++;            }        }    }    return count;} // Driver Codeint main(){    int arr[] = { 1, 2, 3, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << numPairsWithPrimeSum(arr, n);    return 0;}
// Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG {     // Function to check whether a number    // is prime or not    public static boolean isPrime(int num)    {        if (num == 0 || num == 1) {            return false;        }        for (int i = 2; i * i <= num; i++) {            if (num % i == 0) {                return false;            }        }        return true;    }     // Function to count total number of pairs    // of elements whose sum is prime    public static int numPairsWithPrimeSum(        int[] arr, int n)    {        int count = 0;        for (int i = 0; i < n; i++) {            for (int j = i + 1; j < n; j++) {                int sum = arr[i] + arr[j];                if (isPrime(sum)) {                    count++;                }            }        }        return count;    }     // Driver code    public static void main(String[] args)    {        int[] arr = { 1, 2, 3, 4, 5 };        int n = arr.length;        System.out.println(            numPairsWithPrimeSum(arr, n));    }}
# Python3 code to find number of pairs of# elements in an array whose sum is primeimport math # Function to check whether a# number is prime or notdef isPrime(num):         sq = int(math.ceil(math.sqrt(num)))     if num == 0 or num == 1:        return False     for i in range(2, sq + 1):        if num % i == 0:            return False     return True # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n):         count = 0         for i in range(n):        for j in range(i + 1, n):            sum = arr[i] + arr[j]                         if isPrime(sum):                count += 1                     return count # Driver Codearr = [ 1, 2, 3, 4, 5 ]n = len(arr) print(numPairsWithPrimeSum(arr, n)) # This code is contributed by grand_master
// C# code to find number of pairs of// elements in an array whose sum is primeusing System;class GFG{ // Function to check whether a number// is prime or notpublic static bool isPrime(int num){    if (num == 0 || num == 1)    {        return false;    }    for (int i = 2; i * i <= num; i++)    {        if (num % i == 0)        {            return false;        }    }    return true;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr,                                       int n){    int count = 0;    for (int i = 0; i < n; i++)    {        for (int j = i + 1; j < n; j++)        {            int sum = arr[i] + arr[j];            if (isPrime(sum))            {                count++;            }        }    }    return count;} // Driver codepublic static void Main(){    int[] arr = { 1, 2, 3, 4, 5 };    int n = arr.Length;    Console.Write(numPairsWithPrimeSum(arr, n));}} // This code is contributed by Nidhi_Biet
<script>// Javascript code to count of pairs// of elements in an array// whose sum is prime // Function to check whether a// number is prime or notfunction isPrime(num){    if (num == 0 || num == 1) {        return false;    }    for (let i = 2; i * i <= num; i++) {        if (num % i == 0) {            return false;        }    }    return true;} // Function to count total number of pairs// of elements whose sum is primefunction numPairsWithPrimeSum(arr, n){    let count = 0;    for (let i = 0; i < n; i++) {        for (let j = i + 1; j < n; j++) {            let sum = arr[i] + arr[j];            if (isPrime(sum)) {                count++;            }        }    }    return count;} // Driver Code let arr = [ 1, 2, 3, 4, 5 ];let n = arr.length;document.write(numPairsWithPrimeSum(arr, n)); // This code is contributed by _saurabh_jaiswal</script>
5
 
Time Complexity: 
 
Efficient Approach: Precompute and store the primes by using Sieve of Eratosthenes. Now, for every pair of elements, check whether their sum is prime or not.
 
Below code is the implementation of the above approach:
 
C++
Java
Python3
C#
Javascript
// C++ code to find number of pairs// of elements in an array whose// sum is prime#include <bits/stdc++.h>using namespace std; // Function for Sieve Of Eratosthenesbool* sieveOfEratosthenes(int N){    bool* isPrime = new bool[N + 1];    for (int i = 0; i < N + 1; i++) {        isPrime[i] = true;    }    isPrime[0] = false;    isPrime[1] = false;    for (int i = 2; i * i <= N; i++) {        if (isPrime[i] == true) {            int j = 2;            while (i * j <= N) {                isPrime[i * j] = false;                j++;            }        }    }    return isPrime;} // Function to count total number of pairs// of elements whose sum is primeint numPairsWithPrimeSum(int* arr, int n){    int N = 2 * 1000000;    bool* isPrime = sieveOfEratosthenes(N);    int count = 0;    for (int i = 0; i < n; i++) {        for (int j = i + 1; j < n; j++) {            int sum = arr[i] + arr[j];            if (isPrime[sum]) {                count++;            }        }    }    return count;} // Driver Codeint main(){    int arr[] = { 1, 2, 3, 4, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << numPairsWithPrimeSum(arr, n);    return 0;}
// Java code to find number of pairs of// elements in an array whose sum is primeimport java.io.*;import java.util.*; class GFG {    // Function for Sieve Of Eratosthenes    public static boolean[] sieveOfEratosthenes(int N)    {        boolean[] isPrime = new boolean[N + 1];        for (int i = 0; i < N + 1; i++) {            isPrime[i] = true;        }        isPrime[0] = false;        isPrime[1] = false;        for (int i = 2; i * i <= N; i++) {            if (isPrime[i] == true) {                int j = 2;                while (i * j <= N) {                    isPrime[i * j] = false;                    j++;                }            }        }        return isPrime;    }     // Function to count total number of pairs    // of elements whose sum is prime    public static int numPairsWithPrimeSum(        int[] arr, int n)    {        int N = 2 * 1000000;        boolean[] isPrime = sieveOfEratosthenes(N);        int count = 0;        for (int i = 0; i < n; i++) {            for (int j = i + 1; j < n; j++) {                int sum = arr[i] + arr[j];                if (isPrime[sum]) {                    count++;                }            }        }        return count;    }     // Driver code    public static void main(String[] args)    {        int[] arr = { 1, 2, 3, 4, 5 };        int n = arr.length;        System.out.println(            numPairsWithPrimeSum(arr, n));    }}
# Python3 code to find number of pairs of# elements in an array whose sum is prime # Function for Sieve Of Eratosthenesdef sieveOfEratosthenes(N):     isPrime = [True for i in range(N + 1)]             isPrime[0] = False    isPrime[1] = False         i = 2         while((i * i) <= N):        if (isPrime[i]):            j = 2            while (i * j <= N):                isPrime[i * j] = False                j += 1                         i += 1             return isPrime     # Function to count total number of pairs# of elements whose sum is primedef numPairsWithPrimeSum(arr, n):         N = 2 * 1000000    isPrime = sieveOfEratosthenes(N)    count = 0         for i in range(n):        for j in range(i + 1, n):            sum = arr[i] + arr[j]                         if (isPrime[sum]):                count += 1                     return count # Driver code   if __name__=="__main__":         arr = [ 1, 2, 3, 4, 5 ]    n = len(arr)         print(numPairsWithPrimeSum(arr, n)) # This code is contributed by rutvik_56
// C# code to find number of pairs of// elements in an array whose sum is primeusing System; class GFG{     // Function for Sieve Of Eratosthenespublic static bool[] sieveOfEratosthenes(int N){    bool[] isPrime = new bool[N + 1];    for (int i = 0; i < N + 1; i++)    {        isPrime[i] = true;    }    isPrime[0] = false;    isPrime[1] = false;    for (int i = 2; i * i <= N; i++)    {        if (isPrime[i] == true)        {            int j = 2;            while (i * j <= N)            {                isPrime[i * j] = false;                j++;            }        }    }    return isPrime;} // Function to count total number of pairs// of elements whose sum is primepublic static int numPairsWithPrimeSum(int[] arr,                                       int n){    int N = 2 * 1000000;    bool[] isPrime = sieveOfEratosthenes(N);    int count = 0;    for (int i = 0; i < n; i++)    {        for (int j = i + 1; j < n; j++)        {            int sum = arr[i] + arr[j];            if (isPrime[sum])            {                count++;            }        }    }    return count;} // Driver codepublic static void Main(String[] args){    int[] arr = { 1, 2, 3, 4, 5 };    int n = arr.Length;    Console.WriteLine(numPairsWithPrimeSum(arr, n));}} // This code is contributed by 29AjayKumar
<script> // JavaScript code to find number of pairs of// elements in an array whose sum is prime     // Function for Sieve Of Eratosthenes    function sieveOfEratosthenes(N)    {        let isPrime = Array.from({length: N+1},                                 (_, i) => 0);        for (let i = 0; i < N + 1; i++) {            isPrime[i] = true;        }        isPrime[0] = false;        isPrime[1] = false;        for (let i = 2; i * i <= N; i++) {            if (isPrime[i] == true) {                let j = 2;                while (i * j <= N) {                    isPrime[i * j] = false;                    j++;                }            }        }        return isPrime;    }      // Function to count total number of pairs    // of elements whose sum is prime    function numPairsWithPrimeSum(        arr, n)    {        let N = 2 * 1000000;        let isPrime = sieveOfEratosthenes(N);        let count = 0;        for (let i = 0; i < n; i++) {            for (let j = i + 1; j < n; j++) {                let sum = arr[i] + arr[j];                if (isPrime[sum]) {                    count++;                }            }        }        return count;    }    // Driver Code             let arr = [ 1, 2, 3, 4, 5 ];        let n = arr.length;        document.write(        numPairsWithPrimeSum(arr, n)        );            </script>
5
 
Time complexity: O(N^2) 
29AjayKumar
nidhi_biet
grand_master
rutvik_56
code_hunt
_saurabh_jaiswal
Prime Number
sieve
Arrays
Competitive Programming
Mathematical
Arrays
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming