简体   繁体   中英

Test if the number is prime in Java

Test if the number is prime or not:

This is my code:

public static boolean isPrime(int x){
      if(x<=1) 
         return false;
      else if(x==2) 
         return true;
      else {
         for(int i=2; i<=x/2; i++){                        
             if(x%i==0) 
                return false;
         }
         return true;
      }
   }

My question is: the last statement 'return true', if the number is a prime, then no false return, but if the number is not a prime, then during the for loop, there will be a false return. And when the loop is finished, the program execute the statement below for loop--'return true'. So I am wondering if the returned true will cover the returned false that happened during for loop. (Although when I am testing this code, the code works well for testing a number is prime or not, but I don't know why)

return false (或任何return语句)之后,该方法将不执行任何其他操作而return true ,因此在这种情况下不会达到return true ,因此您的代码可以正常工作。

Why do you start the iteration on zero?

Consider what would happen when i = 1 :

if(x % i == 0)    // i = 1, so x % i will be zero
    return false;

Even more, consider what would happen when i = 0 :

if(x % i == 0)    // how would you define x % 0!?

Start the iteration on 2:

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

return语句使方法退出,因此,如果执行“ return false”,则将永远不会执行返回false和return true的方法退出。

return false ends the method. When we say return , that means "stop what you're doing and give this value back to the method that called us."

Cases where this doesn't happen

  • try - finally blocks, any return statement or exception thrown in the finally block of a try block will override the returned value.
  • System.exit , this method never returns, so any statements after an exit call will not be executed.

if(x%i==0) return false;

if this condition comes true then it will return false and will not execute anything after that

and when above condition will be false it wil return true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM