+ 3

# Can anyone help me fix the prime number checker?

https://code.sololearn.com/cqq40eTjD2R8/?ref=app I'm just a beginner so any help is greatly appreciated

2 Answers

+ 6

Some annotations:
Your function isPrime() uses int i as an internal counter. That's okay, but there is no need for the function to take i as an argument. You can just declare it as a local variable:
bool isPrime(int n) {
// local variable
int i = 0;
}
if(n==(2 or 3)) won't work. Both 2 and 3 evaluate to true (1), so "2 or 3" will be true (1) as well and if(n==(2 or 3)) will check if n is true (1), not if n is either 2 or 3. It's better to use if(n == 2 or n == 3) instead.
Make sure to use semicolons instead of commas in the for statement in line 13. Also, i probably shouldn't start with anything less than 3 (you already checked if n is 2 or 3 before).
Your if statement in line 14 has to be wrapped in parentheses.
The else statement in line 16 is wrong. It will check if n is divisible by a number (let's say 3) and if it isn't, it will immediately return true (as in: n is a prime number). But n might be divisible by 17 or 23 for example. You need to check all possible divisors before you can return true. So you should remove the else statement and only if the whole for loop is finished and no divisor was found, you can return true in the very last line.