I'm quite a novice when it comes to C++, and am part of the way through working out a program to identify the first 7 Mersenne Primes. I'm sure I have quite a few syntax errors as well as logic errors but I'm banging my head against the wall when it comes to the logic of the damn thing.

Any help is appreciated.:icon_mrgreen:

``````#include <iostream>

using namespace std;

bool isPrime (long n);
long power2 (long n);

int main()
{
char q;
long n;

cout << "Mersenne Primes" << endl;
cout << right << "n" << "\t\tMersenne Prime" << endl;
cout << "==" << "\t\t==============" << endl << endl;
for (n = 0; n < 1000000; n++) {
cout << right << n;
isPrime(n);
if (isPrime(n) = true) {
cout << power2(n);
}
}
cout << "Press q (or any other key) followed by 'Enter' to quit:" << endl;
cin >> q;
return 0;
}

bool isPrime (long n)
{
//This calculates if a number's mod is greater than, or equal to half of the number.
if (n != 0 && n != 1 && n != 2) {              //get rid of 0, 1, and 2
if ((n / 2) > (n % 2)) {                 //get rid of numbers divisible by 2
if ((n / 3) > (n % 3)) {        //3
if ((n / 5) > (n % 5)) {  //5
if (n > (n % 7)) {  //& 7, calculated this way will take less time.
return true;
}
else if ((n / 7) == (n % 7)) {
return false;
}
}
else if ((n / 5) == (n % 5)) {
return false;
}
}
else if ((n / 3) == (n % 3)) {
return false;
}
}
else if ((n / 2) == (n % 2)) {
return false;
}
}
else if (n == 2 || n == 3 || n == 5 || n == 7) {
return true;
}
}

long power2 (long n)
{
long num = 1;
for (int temp = 0; temp <= n; temp++) {
num *= 2;
}
return num;
}``````

isPrime checks for primes, power2 multiplies 2 by the power of the prime number.

I may be approaching this from the wrong perspective... :-/

Oh, there are constraints as well;
-isPrime and power2 must be used, as well as used for that purpose.
-must use integer arithmetic only, no pow()
-Due today at midnight. :confused:

Been banging my head against this for a while. I thought I'd come here for help.

## All 3 Replies

if ((n / 2) > (n % 2)) { //get rid of numbers divisible by 2

????

if ((n%2)=0) does it, why making it difficult when it isn't?

????

if ((n%2)=0) does it, why making it difficult when it isn't?

Because (n / 2) < (n % 2) will check for a remainder, if there is any then the number isn't cleanly divisible by 2. I don't see how ((n%2)=0) would help me identify that. :X

Well : let your number be 4 with your test you get (4/2)>(4%2) wich becomes 2>0.
(btw in your answer you say < but let us ignore that for the moment)
Now let our number be 5 and do the same (5/2)>(5%2) wich becomes 2>1.
Now tell me wich of those numbers 4 or 5 has a remainder when divided by 2?
I can!
I say 4%2=0 or 5%2=1 so 4 is divisible by 2 and 5 not.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.