- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 product of prime numbers between 1 to n in C++
Suppose we have a number n. We have to find the product of prime numbers between 1 to n. So if n = 7, then output will be 210, as 2 * 3 * 5 * 7 = 210.
We will use the Sieve of Eratosthenes method to find all primes. Then calculate the product of them.
Example
#include<iostream> using namespace std; long PrimeProds(int n) { bool prime[n + 1]; for(int i = 0; i<=n; i++){ prime[i] = true; } for (int i = 2; i * i <= n; i++) { if (prime[i] == true) { for (int j = i * 2; j <= n; j += i) prime[j] = false; } } long product = 1; for (int i = 2; i <= n; i++) if (prime[i]) product *= i; return product; } int main() { int n = 8; cout << "Product of primes up to " << n << " is: " << PrimeProds(n); }
Output
Product of primes up to 8 is: 210
Advertisements