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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program the find two distinct prime numbers with the given product. Let's see some examples.

Input − 21

Output − 3 7

Here, we need to have all the prime numbers that are less than the given product. Once we have those prime numbers, then we can easily find the pair. Follow the below steps to solve the problem.

• Initialize a product and an boolean array to store whether a numbers in the range are prime or not.

• Find all the prime numbers that are less than given product and store them in a array.

• Iterate till given product.

• If the current number is prime and n / current_number is also prime, then check whether they are distinct or not.

• If they are distinct, then print them.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool primes(int n, bool primeStatus[]) {
primeStatus[0] = primeStatus[1] = false;
for (int i = 2; i <= n; i++) {
primeStatus[i] = true;
}
for (int i = 2; i * i <= n; i++) {
if (primeStatus[i] == true) {
for (int j = i * 2; j <= n; j += i)
primeStatus[j] = false;
}
}
}
int main() {
int n = 21;
bool primeStatus[n + 1], pairsFound = false;
primes(n, primeStatus);
for (int i = 2; i < n; i++) {
int pair = n / i;
if (primeStatus[i] && primeStatus[pair] && pair != i && pair * i == n) {
cout << i << " " << pair << endl;
pairsFound = true;
break;
}
}
if (!pairsFound){
cout << "No pairs";
}
return 0;
}

## Output

If you run the above code, then you will get the following result.

3 7

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Published on 29-Dec-2020 10:35:56