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.
Thanks in advance!