[英]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. 我的问题是:最后一个语句“ return true”,如果数字为质数,则没有错误返回,但是如果数字不是质数,则在for循环期间,将有错误返回。 And when the loop is finished, the program execute the statement below for loop--'return true'.
循环结束后,程序将执行以下for循环的语句-'return true'。 So I am wondering if the returned true will cover the returned false that happened during for loop.
所以我想知道返回的true是否将覆盖在for循环期间发生的返回的false。 (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
: 考虑当
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
: 甚至更多,考虑当
i = 0
时会发生什么:
if(x % i == 0) // how would you define x % 0!?
Start the iteration on 2: 从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. return false
结束方法。 When we say return
, that means "stop what you're doing and give this value back to the method that called us." 当我们说
return
,这意味着“停止您正在做的事情,并将此值返回给调用我们的方法”。
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. try
- finally
块,在try
块的finally
块中引发的任何return
语句或异常都将覆盖返回的值。 System.exit
, this method never returns, so any statements after an exit
call will not be executed. System.exit
,此方法从不返回,因此exit
调用后的任何语句都不会执行。 if(x%i==0) return false;
if this condition comes true then it will return false and will not execute anything after that 如果此条件为真,则它将返回false,之后将不执行任何操作
and when above condition will be false it wil return true. 当上述条件为假时,它将返回true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.