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>
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:
Contribute your code and comments through Disqus.
Previous: Write a program in C++ to check if a number is Mersenne number or not.
Next: Write a program in C++ to find Narcissistic decimal numbers within a specific range.
What is the difficulty level of this exercise?
C++ Programming: Tips of the Day
Advantage of switch over if-else statement
Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).
Ref: https://bit.ly/3G0uBqS
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook