# Mersenne Prime Number in C++.

C++Server Side ProgrammingProgramming

## Description

In mathematics, a Mersenne prime is a prime number that is one less than a power of two. That is, it is a prime number of the form Mn = 2n − 1 for some integer n.

Write a C++ program to print all Mersenne Primes smaller than an input positive integer n.

The exponents n which give Mersenne primes are 2, 3, 5, 7,... and the resulting Mersenne primes are 3, 7, 31, 127

## Algorithm

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

## Example

#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;
}

## Output

When you compile and execute the above program. It generates the following output −

Mersenne primes numbers till 100
3 7 31
Published on 31-Oct-2019 05:54:02