﻿ C++ : Generate Mersenne primes within a range of numbers

C++ Exercises: Generate Mersenne primes within a range of numbers

C++ Numbers: Exercise-36 with Solution

Write a C++ program to generate Mersenne primes within a range of numbers.

Sample Solution:

C++ Code :

``````#include<bits/stdc++.h> // Include entire standard library
using namespace std; // Using the standard namespace

void GenAllPrim(int n1, bool prarr1[]) // Function to generate all prime numbers until 'n1'
{
for (int i=0; i<=n1; i++) // Loop through array prarr1 and initialize all elements as true
prarr1[i] = true;

for (int p=2; p*p<=n1; p++) // Loop to mark non-prime numbers using Sieve of Eratosthenes algorithm
{
if (prarr1[p] == true) // If the number is marked as prime
{
for (int i=p*2; i<=n1; i += p) // Mark all multiples of 'p' as non-prime
prarr1[i] = false;
}
}
}

void chkMerPrime(int nm) // Function to check and print Mersenne prime numbers up to 'nm'
{
bool prarr1[nm+1]; // Declare an array to hold prime number information up to 'nm'
GenAllPrim(nm, prarr1); // Call function to generate prime numbers

for (int j=2; ((1<<j)-1) <= nm; j++) // Loop through potential Mersenne numbers: (2^j - 1)
{
long long num = (1<<j) - 1; // Calculate potential Mersenne number
if (prarr1[num]) // Check if the number is a prime number
cout <<" "<< num << " "; // If prime, print it as a Mersenne prime
}
}

int main() // Main function
{
int n; // Declare variable to store upper limit of the range
cout << "\n\n Generate Mersenne primes within a range of numbers:\n"; // Display purpose
cout << "--------------------------------------------------------\n"; // Display purpose
cout << " Input an upper limit [range from 1 to upper limit]: "; // Prompt user for input
cin >> n; // Input the upper limit
cout << " Mersenne prime numbers are: " << endl; // Display purpose
chkMerPrime(n); // Call function to check Mersenne primes within the given range
cout << endl << endl; // Display purpose
}
``````

Sample Output:

```Generate Mersenne primes within a range of numbers:
--------------------------------------------------------
Input a upper limit [range from 1 to upper limit]: 200
Mersenne prime numbers are:
3  7  31  127
```

Flowchart:

C++ Code Editor: