Hi! I'm having a bit of an issue with my prime number counter/calculator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
bool isprime (int a)
{
int c;
bool first;
for (int b = 2; b < a; b++ ) {
c = (a%b);
if (c == 0) {
first = 0; }
}
if (first == 1) {
cout << "The number " << a << " is prime." << endl; }
else
cout << "The number " << a << " is not prime." << endl;
return first;
}
int main ()
{
int x, y, z;
start:
cout << "Would you like to test a range of numbers for being prime, or just one number." << endl << setw (4) << "(1) Range of numbers." << endl << setw(4) << "(2) Just one number." << endl << endl << "Make your selection: ";
cin >> x;
switch (x) {
case 1:
cout << "Please enter the number up to which you'd like to get the output:";
cin >> y;
for (int g = 1; g <= y; g++) {
isprime (g); }
break;
case 2:
cout << "Enter the number you'd like to test: " ;
cin >> y;
isprime (y);
break;
default: cout << "You have made an invalid selection. Please press enter to try again." << endl << endl;
cin.get ();
cin.get ();
goto start;
}
cin.get ();
cin.get ();
return 0;
}
|
So, it works perfectly fine when I select option 2. It reads the number, and returns a correct value. I tested it for a whole bunch of numbers. Buut, here's the problem. When I do the range option, it reads the first three numbers (1, 2, 3) as primes, which is correct, then 4 as a non-prime, and then 5 as a non-prime as well.
Wait, what?
Output looks like this:
Make your selection: 1
Please enter the number up to which you'd like to get the output:10
The number 1 is prime.
The number 2 is prime.
The number 3 is prime.
The number 4 is not prime.
The number 5 is not prime.
The number 6 is not prime.
The number 7 is not prime.
The number 8 is not prime.
The number 9 is not prime.
The number 10 is not prime.
What I
think is happening is that the boolean prime is not clearing every time the function finishes executing. So, is there a way to 'clear' the function after it's used? Would isprime(void) work in the main ()?
EDIT: Well, I dunno if it counts as solved, but I did manage to do a workaround. I simply placed a
first = 1;
right before the
return first
statement.