C ++中等于其给定N的最大素数

在这个问题上,给我们一个数字n。我们的任务是找到与给定N相等的素数的最大数目。

在这里,我们将找到相加后的最大质数个数。

质数是可以自己除以一个的那些数。

让我们举个例子来了解问题-

输入-N = 9

输出-4

说明-

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.

使用的最大质数数量将取决于可以添加多少个最小质数来求和。

因此,最小的质数是2。连续的较大质数是3,这很奇怪。

因此,如果在计算总和时仅使用2和3,则计数将达到最大值。基于此,我们可以将问题分为两种情况-

情况1-如果N为偶数,则总和中的所有素数均为2。因此,计数将为n / 2。

情况2-如果N为奇数,则总和中的所有素数都将是2的质数,除了一个是3。因此,计数将是(n-1 / 2)。

示例

程序查找最大素数,其和等于C ++中的给定N

#include <iostream>
using namespace std;
int maxPrimeCount(int n){
   //对于奇数情况,结果将与(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;
}

输出结果

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