So for some reason it keeps printing out that 2 and 3 are not prime numbers. wtf?
here's my code:
int main(){
int n;
while(cin >> n){
if(isprime(n))
cout << "This is a prime number" << endl;
else
cout << "This is not a prime number" << endl;
}
return 0;
}
bool isprime(int n){
for(int i = 2; i < sqrt(n); i++){
if(n % i == 0){
return false;
break;
}
else
return true;
}
}
and here is my output:
1
This is not a prime number
2
This is not a prime number
3
This is not a prime number
4
This is not a prime number
5
This is a prime number
6
This is not a prime number
7
This is a prime number
8
This is not a prime number
9
This is a prime number
my prof is defining 1 as not being a prime number, fyi.
thanks in advance
int main() {
int n;
while (cin >> n) {
if (isprime(n))
cout << "This is a prime number" << endl;
else
cout << "This is not a prime number" << endl;
}
return 0;
}
bool isprime(int n) {
for (int i = 2; i < sqrt(n); i++) {
if (n % i == 0) {
returnfalse;
break; //never reach this
} else //note that you are still inside the loop
returntrue;
}
//missing return statement
}
for the case of 2 and 3, you never get inside the loop.
the function is missing a return statement there, so it's undefined behaviour.
Also notice that you say that 9 is a prime number.
to restate the above explicitly in case you don't see it:
sqrt 2 is 1.something, i is 2, 2 is not less than 1.x same for 3 AND for 4. i is 2 and sqrt 4 is 2 and 2 is not < 2. For 0 and larger input, your function will not start to work until 5 where i is 2 and sqrt 5 is larger than 2. For 0,1,2,3, and 4 your function is effectively this because the loop condition is false right away:
bool isprime(int n)
{
;
}
which is 1/2 the problem.
for 5,
i is 2, sqrt 5 is 2.x, loop enters, if 5%2 == 0 (it does not) so else is triggered, true is returned. (this HAPPENS to be correct, but as you can see for other values, you only get the right answer sometimes).
one way to fix this is to just return the correct answers for 0, 1, and 2, then adjust your logic to work for 3 and larger.