I’m trying to sort out some homework regarding “repetition” with the while statement. The homework is asking me to input a number and tell if said number is prime. So far, I’ve come with this:
class Prime {
boolean esPrime(int n) {
boolean prime = true;
int divisor = 2;
while (prime && divisor != n) {
if (n % divisor == 0) {
prime = false;
} else {
divisor++;
}
}
return prime;
}
}
Then I stated this “boolean test” in the main method to check if that piece of code worked:
boolean testEsPrime = esPrime(2) == false;
public static void main(String[] args) {
Prime p = new Prime();
System.out.println("testEsPrime = " + p.testEsPrime);
}
And whenever I run it I get false and I can’t seem to be able to spot the error. Any clue why this happens?
It’s not the most efficient code in the world, but it works for me (see below). I’m not sure what the problem is here! Incidentally, you only need to test
2and odd factors up to the square root of the thing you’re testing, and a more efficient approach in general (for determining what numbers are primes in bulk) is to use a Sieve of Erastothenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes).The reason you get
falsefor the test you do is thatesPrime(2) == falseisfalse– that is,esPrime(2) == true.Output:
esPrime(2) = true
esPrime(3) = true
esPrime(4) = false
esPrime(5) = true
esPrime(6) = false
esPrime(7) = true
esPrime(8) = false
esPrime(9) = false