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

## Problem statement

Given a positive integer N > 1. Find the maximum count of prime numbers whose sum is equal to given N

## Example

If N = 8 then answer will be 4 as −
2 + 2 + 2 + 2 = 8

## Algorithm

• For maximum number of primes whose sum is equal to given n, prime numbers must be as small as possible
• 2 is smallest possible prime number and is an even number. Next prime number greater than 2 is 3 which is odd. So, for any given n there are two conditions, either n will be odd or even −
• If n is an even, then n/2 will be the answer
• If n is an odd, then floor(n/2) will be the answer

## Example

#include <bits/stdc++.h>
using namespace std;
int getMaxPrimes(int n) {
if (n % 2 == 0) {
return n / 2;
}
return floor(n/2);
}
int main() {
int n = 8;
cout << "Maximum prime numbers to get sum " << n << "
are = " << getMaxPrimes(n) << endl;
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Maximum prime numbers to get sum 8 are = 4
Published on 21-Jan-2020 11:11:47
Advertisements