﻿ 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 program in C++ to generate Mersenne primes within a range of numbers.

Sample Solution:

C++ Code :

``````#include<bits/stdc++.h>
using namespace std;

void GenAllPrim(int n1, bool prarr1[])
{
for (int i=0; i<=n1; i++)
prarr1[i] = true;

for (int p=2; p*p<=n1; p++)
{
if (prarr1[p] == true)
{
for (int i=p*2; i<=n1; i += p)
prarr1[i] = false;
}
}
}
void chkMerPrime(int nm)
{
bool prarr1[nm+1];
GenAllPrim(nm,prarr1);
for (int j=2; ((1<<j)-1) <= nm; j++)
{
long long num = (1<<j) - 1;
if (prarr1[num])
cout <<" "<< num << " ";
}
}
int main()
{
int n ;
cout << "\n\n Generate Mersenne primes within a range of numbers:\n";
cout << "--------------------------------------------------------\n";
cout << " Input a upper limit [range from 1 to upper limit]: ";
cin>>n;
cout << " Mersenne prime numbers are: "<<endl;
chkMerPrime(n);
cout<<endl<<endl;
}
``````

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:

What is the difficulty level of this exercise?

﻿

## C++ Programming: Tips of the Day

How to use the PI constant in C++?

On some (especially older) platforms (see the comments below) you might need to

#define _USE_MATH_DEFINES and then include the necessary header file:
`#include<math.h>`

and the value of pi can be accessed via:

`M_PI`

In math.h (2014) it is defined as:

`# define M_PI           3.14159265358979323846  /* pi */`

but check your math.h for more. An extract from the "old" math.h (in 2009):

```/* Define _USE_MATH_DEFINES before including math.h to expose these macro
* definitions for common math constants.  These are placed under an #ifdef
* since these commonly-defined names are not part of the C/C++ standards.
*/```

However:

1. on newer platforms (at least on my 64 bit Ubuntu 14.04) I do not need to define the _USE_MATH_DEFINES
2. On (recent) Linux platforms there are long double values too provided as a GNU Extension:
`# define M_PIl          3.14159265358979323846`

Ref: https://bit.ly/3G4BgzQ