
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the Product of first N Prime Numbers 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
- Related Articles
- Find product of prime numbers between 1 to n in C++
- Sum of the first N Prime numbers
- Find two distinct prime numbers with given product in C++
- Find the mean of first five prime numbers
- Find the average of first N natural numbers in C++
- Product of first N factorials in C++
- Find two distinct prime numbers with given product in C++ Program
- Product of all prime numbers in an Array in C++
- C++ program to find the first digit in product of an array of numbers
- Find the good permutation of first N natural numbers C++
- Find count of Almost Prime numbers from 1 to N in C++
- Program to find first N Iccanobif Numbers in C++
- Find m-th summation of first n natural numbers in C++
- Program to find sum of first n natural numbers in C++
- Absolute Difference between the Product of Non-Prime numbers and Prime numbers of an Array?

Advertisements