在数学中,梅森素数是小于2的幂的素数。即,对于某个整数n,它是形式为Mn = 2n-1的质数。
编写C ++程序以打印所有小于输入正整数n的Mersenne Prime。
给出梅森素数的指数n为2,3,5,7,...,得到的梅森素数为3,7,31,127
1. Generate all the primes less than or equal to the given number n 2. Iterate through all numbers of the form 2n-1 and check if they are primes or not
#include <iostream> #include <algorithm> using namespace std; void generatePrimes(bool *primes, int n){ fill(primes, primes + n + 1, true); for (int p = 2; p * p <= n; ++p) { if (primes[p] == true) { for (int i = p * 2; i <= n; i += p) { primes[i] = false; } } } } void mersennePrimes(int n){ bool primes[n + 1]; generatePrimes(primes, n); for (int i = 2; ((1 << i) - 1) <= n; ++i) { int num = (1 << i) - 1; if (primes[num]) { cout << num << " "; } } cout << endl; } int main(){ int n = 100; cout << "Mersenne primes numbers till " << n << endl; mersennePrimes(n); return 0; }
输出结果
当您编译并执行上述程序时。它生成以下输出-
Mersenne primes numbers till 100 3 7 31