在 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.