Find two distinct prime numbers with given product in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find two distinct prime numbers with given product.

For this we will be provided with an integer value. Our task is to find the two prime integer values such that their product is equal to the given value.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
//generating prime numbers less than N.
void findingPrimeNumbers(int n, bool calcPrime[]) {
   calcPrime[0] = calcPrime[1] = false;
   for (int i = 2; i <= n; i++)
      calcPrime[i] = true;
   for (int p = 2; p * p <= n; p++) {
      if (calcPrime[p] == true) {
         for (int i = p * 2; i <= n; i += p)
            calcPrime[i] = false;
      }
   }
}
//printing the valid prime pair
void calcPairPrime(int n) {
   int flag = 0;
   bool calcPrime[n + 1];
   findingPrimeNumbers(n, calcPrime);
   for (int i = 2; i < n; i++) {
      int x = n / i;
      if (calcPrime[i] && calcPrime[x] and x != i and x * i == n) {
         cout << i << " " << x;
         flag = 1;
         return;
      }
   }
   if (!flag)
      cout << "No prime pair exist";
}
int main() {
   int n = 24;
   calcPairPrime(n);
   return 0;
}

Output

No prime pair exist
raja
Published on 19-Aug-2020 10:34:06
Advertisements