确定素数Java [英] Determining Prime Numbers Java
问题描述
我正在编写一个程序,它将整数作为输入,并输出一个消息,无论输入的整数是否为素数。我使用的算法如下...... 要求: n> 0,要求: isPrime< - true, i = 2到sqrt(n)做,如果 n%i = 0 那么 isPrime< - false 结束如果和结束然后打印该号码是否为Prime。这是我的代码到目前为止,代码不起作用,我无法找到问题。
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, for i=2 to sqrt(n) do, if n%i=0 then isPrime <- false end if and end for Then 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.
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如果有人可以提供帮助,我将不胜感激!谢谢!
I would be grateful if someone could help, Thanks!
推荐答案
你的问题在于这一行:
if (isPrime = true){
你做了一个作业,而不是比较 true
,所以语句总是 true
。
You made an assignment, instead of comparing to true
, so the statement is always true
.
使用 ==
来比较布尔值,或者更好,因为 isPrime
已经是布尔值
:
Use ==
to compare boolean values, or better yet, since isPrime
is already a boolean
:
if (isPrime){
这篇关于确定素数Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!