Maximum Primes whose sum is equal to given N in C++


In this problem, we are given a number n. Our task is to find the maximum count of primes whose sum is equal to given N.

Here, we will find the maximum number of prime numbers that when added will be equal to the number.

The prime number are those number which can be divide by either themselves or one.

let's take an example to understand the problem −

Input − N = 9

Output − 4

Explanation

9 can be repressed as the sum of prime numbers in the following ways:
2, 2, 2, 3
3, 3, 3
2, 2, 5
2, 7
Out of these the maximum number of primes used is 4.

The maximum number of prime numbers that are used will be based on how many smallest prime numbers can be added to make the sum.

So, the smallest prime number is 2. And the successive greater prime number is 3, which is odd.

So, the count will be maxed if we use only 2’s and 3’s while calculating the sum. Based on this we can divide the problem, in two cases −

Case 1 − if N is even, all prime numbers in the sum will be 2’s. So, the count will be n/2.

Case 2 − if N is odd, all prime numbers in the sum will be 2’s except one which will be 3. So, the count will be (n-1/2).

Example

Program to find Maximum Primes whose sum is equal to given N in C++

 Live Demo

#include <iostream>
using namespace std;
int maxPrimeCount(int n){
   //For odd case the result will same as (n-1)/2
   return n / 2;
}
int main(){
   int n = 9;
   cout<<"The maximum number of primes whose sum is equal to "<<n<<" is "<<maxPrimeCount(n);
   return 0;
}

Output

The maximum number of primes whose sum is equal to 9 is 4

Updated on: 03-Jun-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements