Hi i've searched through some articles and i think the mathematical part of my code is correct, but it doesnt run as expected. many thanks in advanced.
edit: the program is required to calculate all the primes between 2 and 2000.
Weird, I don't see any reason why this wouldn't output. Try throwing a random cout statement at the very beginning of the function and see if that works. If that doesn't, then try putting one in main.
#include <iostream>
usingnamespace std;
void prime()
{
cout<<"prime function running";
bool primecheck = true;
int number=2000;
do
{
for (int checker=2; checker<=number; checker++)
{
if (number % checker == 0)
{
primecheck = false;
number--;//added this as once if found if 'number' is not prime we can move on the the next
break;
}
}
if (primecheck)
cout<<number<<" is prime ";
cout<<number<<endl;//to see if the number being checked is changing
}while (number>1);
}
int main()
{
cout<<"main running";
prime();
system("pause");
return 0;
}
Sorry, I actually meant at line 23. But since you didn't mention it in the list of lines that does get outputted, I can assume line 23 is never hit.
primecheck is never set back to true when testing a new number, so it's going to be remain false after the first composite number is hit, which how you have this set up will be the very first number (2000). Since primecheck is never true, that statement will never get hit.
#include <iostream>
usingnamespace std;
void prime()
{
cout<<"prime function running";
bool primecheck;
int number=2000;
do
{
primecheck = true;//reseting prime check for every new number
for (int checker=2; checker<=number; checker++)//check against all the integers less than number
{
if (number%checker==0)//if the remainder of the division is zero i.e. it does divide then....
{
primecheck = false;//...its not prime
number--;//added this as once if found if 'number' is not prime we can move on the the next
break;
}
}
if (primecheck == true)//!!**!!**this is never true**!!**!!**!!
{
cout<<number<<" is prime";
}
}while (number>1);
}
int main()
{
cout<<"main running";
prime();
system("pause");
return 0;
}
Several errors.
The for-loop should have checker<number, not <=.
The boolean primecheck needs to be reset for each new number.
The number-- needs to be executed regardless of whether or not the number is prime.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
do
{
primecheck = true;
for (int checker=2; checker<number; checker++)
{
if (number % checker == 0)
{
primecheck = false;
break;
}
}
if (primecheck)
cout << number << " is prime ";
number--;
} while (number>1);