确定质数 Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18625793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Determining Prime Numbers Java
提问by CBH
I am writing a program that takes as input an integer, and outputs a message whether the integer entered is prime or not. The algorithm I am using is as follows... Require:n>0, Require:isPrime <- true, fori=2 to sqrt(n) do, ifn%i=0 thenisPrime <- false end ifand end forThen Print whether the number is Prime or not. Here is my code so far, the code is not working and I am not able to find the problem.
我正在编写一个程序,该程序将一个整数作为输入,并输出一条消息,无论输入的整数是否为素数。我使用的算法如下... Require:n>0, Require:isPrime <- true, fori=2 to sqrt(n) do, ifn%i=0 thenisPrime <- false end ifand end forThen 打印数字是否为质数。到目前为止,这是我的代码,代码不起作用,我无法找到问题。
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int n;
System.out.println("Input a positive integer");
n = kb.nextInt();
while (n>0){
boolean isPrime = true;
for (int i =2; i <= n/2;i++){
if(n % i == 0){
isPrime = false;
break;
}
}
if (isPrime = true){
System.out.println("The integer, " + n + ", is a prime");
break;
}
else{
System.out.println("The integer, " + n + ", is not a prime");
break;
}
}
}
}
I would be grateful if someone could help, Thanks!
如果有人能帮忙,我将不胜感激,谢谢!
采纳答案by rgettman
Your problem lies with this line:
你的问题在于这一行:
if (isPrime = true){
You made an assignment, instead of comparing to true
, so the statement is always true
.
您进行了赋值,而不是与 进行比较true
,因此语句始终为true
。
Use ==
to compare boolean values, or better yet, since isPrime
is already a boolean
:
使用==
比较布尔值,或更好,但因为isPrime
已经是boolean
:
if (isPrime){
回答by Celeritas
In the text you say the algorithm you intend to implement checks integers up to the square root of n
but your code is going all the way up to n/2
(see the for loop).
在文本中,你说你打算实现的算法检查整数的平方根,n
但你的代码一直在n/2
(参见 for 循环)。
The reason your current code isn't working is because if (isPrime = true)
is an assignment operation and should be comparison if (isPrime == true)
note the two equal signs.
您当前的代码不起作用的原因是因为if (isPrime = true)
是赋值操作,应该比较if (isPrime == true)
注意两个等号。