[英]Prime Number checker is not working
This is the code for a function that is supposed to return true if the input is prime and returns false if it is not. 这是一个函数的代码,如果输入为素数,则应返回true,否则返回false。
This is how I intended for it to work: lets say that y = 7, the loop starts with n=1. 这就是我打算的工作方式:假设y = 7,循环从n = 1开始。 Since 1(n) is less that 7(y) the loop can iterate. 由于1(n)小于7(y),因此循环可以迭代。 The program checks if y divided by n has a remainder of 0, meaning that n is a factor of y. 程序检查y除以n是否有0的余数,这意味着n是y的因数。 If it is true, then it checks to see if the factor does not equal 1 or y (7), because if they dont then that means that y has more factors other than its self and 1, meaning that it is not prime, so it should automatically end the function and return false. 如果为真,那么它将检查该因子是否等于1或y(7),因为如果它们不等于1,则意味着y除了自身和1之外还有更多因子,这意味着它不是素数,因此它应该自动结束函数并返回false。 but since 7 has only two factors, 1 and 7, and they either equal 1 or itself (y) then after the end of the loop, it should return true. 但由于7只有两个因子1和7,并且它们等于1或自身(y),因此在循环结束后,它应该返回true。
I don't understand why it isn't working. 我不明白为什么它不起作用。
public static boolean checkIfPrime(long y) {
for ( long n =1L; n <= y; n++) {
if(y%n == 0) {
if( n != 1L || n != y) {
return false;
}
}
}
return true;
}
With a few optimizations the code will be like this 经过一些优化,代码将像这样
static boolean isPrime(long n){
long lim = (long) Math.sqrt(n);
if(n%2 == 0 && n != 2)
return false;
for (int i = 3; i <= lim; i=i+2)
if(n%i == 0)
return false;
return true;
}
This code: 这段代码:
Remove equal to operator in n <= y. 在n <= y中删除等于运算符。 Start your loop from 2. It must be like this. 从2开始循环。它必须是这样的。 ( long n =2; n < y; n++) (long n = 2; n <y; n ++)
For what you are trying to achieve, pseudo code in my opinion should look like this: 对于您要实现的目标,我认为伪代码应如下所示:
set a flag = true;
Loop from 2 to y-1{
if(y%n==0){
flag = false
break; // Very important
}
}
check flag condition & return (if some othe computation is required) or just return flag
if( n != 1L || n != y) : is adding a check condition unnecessarily to every iteration. if(n!= 1L || n!= y):不必要在每次迭代中添加检查条件。 try to avoid it. 尽量避免它。
Why use a flag instead of direct return statement ? 为什么使用标志代替直接返回语句? Just a preference, a direct return definitely would work in this case. 只是偏爱,在这种情况下,直接回报肯定会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.