Prime numbers after prime P with sum S in C++


In this problem, we are given three numbers, sum S, prime P, and N. Our task is to find all N prime numbers greater than P whose sum is equal to S.

Let’s take an example to understand our problem

Input: N = 2, P = 5, S = 18
Output: 7 11
Explanation: Prime numbers greater than 5 : 7 11 13
Sum = 7 + 11 = 18

To solve this problem, we have to find all prime numbers between P and S. And then find N prime numbers which sum up to S. For this we will use backtracking.

Program to show the implementation of our solution

Example

 Live Demo

#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;
}

Output

3 Prime numbers greater than 3 with sum = 23 are :
5   7   11
raja
Published on 03-Feb-2020 10:52:07
Advertisements