
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Two Distinct Prime Numbers with Given Product in C++
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.
#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.