Count numbers which can be represented as sum of same parity primes in C++


We are given an array Arr[] of positive integers of size N. The goal is to count the number of elements in that array which can be represented as sum of parity primes, that is they can be shown as a sum of the same prime number. Ex; 4= 2+2, 6=3+3 or 2+2+2

The sum of any two odd or even prime numbers will always be even. And except 0 and 2 all even numbers can be represented as sum of same primes.

Let’s understand with examples.

Input 

Arr[] = { 2, 5, 10, 15, 20, 25 }

Output 

Number which satisfy condition : 3

Explanation 

Numbers as sum of same primes:
Arr[0] = 2 X count=0
Arr[1] = 5 : X count=0
Arr[2] = 10 :5+5 count=1
Arr[3] = 15 : X count=1
Arr[4] = 20 : 5+5+5+5 count=2
Arr[5] = 25 : X count=2

Input 

Arr[] = { 0, 2, 4, 11, 13}

Output 

Number which satisfy condition : 1

Explanation 

Numbers as sum of same primes:
Arr[0] = 0 : X count=0
Arr[1] = 2 : X count=0
Arr[2] = 4 : 2+2 count=1
Arr[3] = 11 : X count=1
Arr[4] = 13 : X count=1

Approach used in the below program is as follows

  • We take an array of positive integers of length N..

  • Function sumofparityPrimes(int arr[],int n) takes array and n as input and returns the number of elements that can be represented as sum of parity primes.

  • Take the initial variable count as 0 for such numbers..

  • Traverse array using for loop.

  • For each element if it is even ( arr[i]%2==0 ).

  • Then check it is neither 0 nor 2. If true increment count.

  • Return the count as result at the end of for loop.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int sumofparityPrimes(int arr[],int n){
   int count = 0;
   for(int i=0;i<n;i++){
      if(arr[i]%2==0) //num is even only{
         if(arr[i]!=0){
            if(arr[i]!=2)
               { count++; } //neither 0 nor 2
         }
      }
   }
   return count;
}
int main(){
   int Arr[]={ 12, 5 , 15, 8, 100, 40 };
   int Length= sizeof(Arr)/sizeof(Arr[0]);
   cout <<endl<< "Number which satisfy condition : "<<sumofparityPrimes(Arr,Length);
   return 0;
}

Output

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

Number which satisfy condition : 4

Updated on: 31-Oct-2020

100 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements