在 C++ 中找到前 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

更新於: 19-12-2019

280 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.