使用 C++ 查詢 1 到 n 之間的素數乘積
假設我們有一個數字 n。我們要找出 1 到 n 之間的素數乘積。因此,如果 n = 7,則輸出為 210,因為 2 * 3 * 5 * 7 = 210。
我們將使用埃拉託斯特尼篩法來找出所有素數。然後計算它們的乘積。
示例
#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
廣告