在C ++中查找前N个质数的乘积

假设我们有一个数字n。我们必须找到1到n之间的质数的乘积。因此,如果n = 7,则输出将为210,因为2 * 3 * 5 * 7 = 210。

我们将使用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
猜你喜欢