在这个问题中,我们给了三个数字,分别为S,素数P和N。我们的任务是找到所有大于P且总和等于S的N个素数。
让我们以一个例子来了解我们的问题
Input: N = 2, P = 5, S = 18 Output: 7 11 Explanation: Prime numbers greater than 5 : 7 11 13 Sum = 7 + 11 = 18
为了解决这个问题,我们必须找到P和S之间的所有素数。然后找到总计为S的N个素数。为此,我们将使用回溯。
显示我们解决方案实施情况的程序
#include <iostream> #include <vector> #include <cmath> using namespace std; vector<int> set; vector<int> primeNo; bool isPrimeNumber(int x) { int sqroot = sqrt(x); bool flag = true; if (x == 1) return false; for (int i = 2; i <= sqroot; i++) if (x % i == 0) return false; return true; } void printPrimes() { int length = set.size(); for (int i=0; i<length; i++) cout<<set[i]<<"\t"; cout<<endl; } void GeneratePrimeSum(int total, int N, int S, int index) { if (total == S && set.size() == N) { printPrimes(); return; } if (total > S || index == primeNo.size()) return; set.push_back(primeNo[index]); GeneratePrimeSum(total+primeNo[index], N, S, index+1); set.pop_back(); GeneratePrimeSum(total, N, S, index+1); } void PrimesWithSum(int N, int S, int P) { for (int i = P+1; i <=S ; i++) { if (isPrimeNumber(i)) primeNo.push_back(i); } if (primeNo.size() < N) return; GeneratePrimeSum(0, N, S, 0); } int main() { int S = 23, N = 3, P = 3; cout<<N<<" Prime numbers greater than "<<P<<" with sum = "<<S<<" are :\n"; PrimesWithSum(N, S, P); return 0; }
输出结果
3 Prime numbers greater than 3 with sum = 23 are : 5 7 11