I am practicing past exam papers for a basic java exam, and I am finding it difficult to make a for loop work for testing whether a number is prime. I don’t want to complicate it by adding efficiency measures for larger numbers, just something that would at least work for 2 digit numbers.
At the moment it always returns false even if n IS a prime number.
I think my problem is that I am getting something wrong with the for loop itself and where to put the “return true;” and “return false;”… I’m sure it’s a really basic mistake I’m making…
public boolean isPrime(int n) {
int i;
for (i = 2; i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
The reason I couldn’t find help elsewhere on stackoverflow is because similar questions were asking for a more complicated implementation to have a more efficient way of doing it.
Your
forloop has a little problem. It should be: –Of course you don’t want to check the remainder when
nis divided byn. It will always give you1.In fact, you can even reduce the number of iterations by changing the condition to: –
i <= n / 2. Sincencan’t be divided by a number greater thann / 2, except when we considern, which we don’t have to consider at all.So, you can change your
forloop to: –