 Prime Directive: why return true below the for loop

https://gist.github.com/d1030a81d8b94fb672cf1854bf776b4e

I’m confused as to why we have to return true below the for loop, as opposed to making it part of the for loop as an if:else statement.

For example, when I test the below code, the method produces false if I input 7 when testing for prime.

public boolean isPrime(int number){
if (number == 2){
return true;
} else if (number < 2){
return false;
}

for(int i=2; i<number; i++){
if(number%i==0){
return false;
} else {
return true;
}

}

}

}

Remember that once a return statement is executed, the method is immediately exited, meaning no more code inside that method will be run.

If we simply used an else block to return true;, our loop would return false for even numbers and true for odd numbers, since we are effectively checking if number % 2 == 0. This is because the return statements cause the loop to iterate only once. However, in our for loop, we want to check if number is evenly divisible by any number from 2 to number - 1.

I’m not sure why your code is returning false for an input of 7, as it should have returned true. Nevertheless, your code would still not work as intended. For example, take the number 9 as your input and walk step-by-step through your code. You’ll get an unexpected result. How could you fix this? (Hint: refer to the explanation I provided above.)

Welcome to the forums!

1 Like