ภาพรวมปัญหา
ได้รับ 3 ตัวเลข: ผลรวม S, จำนวนเฉพาะ P, และ N ต้องหา N จำนวนเฉพาะที่มากกว่า P และผลรวมเท่ากับ S
ตัวอย่าง
Input: N = 2, P = 5, S = 18 Output: 7 11 Explanation: จำนวนเฉพาะ > 5: 7, 11, 13 → 7 + 11 = 18
วิธีแก้ปัญหา
- หาจำนวนเฉพาะทั้งหมดระหว่าง P ถึง S
- ใช้ Backtracking หาชุด N ตัวที่ผลรวมเท่ากับ S
ตัวอย่างโค้ด C++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<int> set;
vector<int> primeNo;
bool isPrimeNumber(int x) {
int sqroot = sqrt(x);
if (x == 1) return false;
for (int i = 2; i <= sqroot; i++)
if (x % i == 0) return false;
return true;
}
void printPrimes() {
for (int i = 0; i < set.size(); 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