Question for the return value of PrimeDirective boolean

Hello, so I have a question of how this code works and why.
This is my code:

  public boolean isPrime(int number) {
    // checks if Prime is 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;
      }
      return true;
    }
 //   return true;
}

This code wont compile without the last return (commented at the moment), and it says its missing a return value.
It will run, when I uncomment the last return statement, and it looks like it will give me the correct result no matter if i return true or false at the last statement.

Why is this? Shouldnt it just take the return statement from earlier whenever the iteration conditions are meet?
Why does it override the last return value and give me the correct result?

A couple of things in your code may not be working.

if (number == 2) {
      return true;
    } else if ( number < 2 ) {
      return false;
    }

here, you are implicitly stating that you promise to add a return value if both these conditions are not met. The compiler is fuzzy on what may happen in your loop, so it will not like it if it doesn’t have something to return outside of it (that’s why it’s useful to set a trigger value).

In terms of your loop:

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

The way it’s written currently, it will not loop. Because in the very first iteration, if the condition is not met, it will return true. This is not so much something that will throw a literal error, but it will not achieve what you want.

Welcome to the forums :slight_smile:

2 Likes