สมมติว่าเรามีตัวเลข n เราต้องหาผลคูณของจำนวนเฉพาะระหว่าง 1 ถึง n ดังนั้นถ้า n =7 ผลลัพธ์จะเป็น 210 เช่น 2 * 3 * 5 * 7 =210
เราจะใช้วิธี Sieve of Eratosthenes เพื่อค้นหาจำนวนเฉพาะทั้งหมด แล้วคำนวณผลของมัน
ตัวอย่าง
#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);
} ผลลัพธ์
Product of primes up to 8 is: 210