Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm tích các số nguyên tố từ 1 đến n trong C++


Cho n, tìm tích các số nguyên tố từ 1 đến n. Ví dụ n=7 → 2*3*5*7=210.

Dùng sàng Eratosthenes tìm số nguyên tố, sau đó tính tích.

Ví dụ

#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); }

Kết quả

Product of primes up to 8 is: 210