[英]Java: Prime Number Program Not Working
Why does the int j
only get the value 2? 为什么int j
只得到值2? Doesn't (int)realNum
mean that it must be a natural number? (int)realNum
是否意味着它必须是自然数?
Scanner basicNum = new Scanner(System. in );
String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");
int realNum = Integer.parseInt(insertNum);
int j = realNum = 1;
if (realNum < 10000) {
while ((realNum / j == (int) realNum)) {
j++;
}
System.out.println(j);
if (j > 2) {
JOptionPane.showMessageDialog(null, "It is not a prime!!");
}
if (j < 2) {
JOptionPane.showMessageDialog(null, "It is a prime!");
}
} else {
JOptionPane.showMessageDialog(null, "Too large number!");
}
int j = realNum = 1;
sets j
and realNum
to 1. 将j
和 realNum
为1。
So realNum / j == (int)realNum
is true until j
is greater than 1. Hence your output. 因此realNum / j == (int)realNum
直到j
大于1才成立。
The (int)
prefix on (int)realNum
is superfluous since realNum
is already an int
type. 因为realNum
已经是int
类型,所以(int)realNum
上的(int)
前缀是多余的。
Also realNum / j
will be evaluated in integer arithmetic: any remainder is truncated. 同样, realNum / j
将以整数算术求值:任何余数都将被截断。
In Java 8, you can easily do it like this: 在Java 8中,您可以像这样轻松地做到这一点:
boolean isPrime(final int n) {
return IntStream.range(2, n / 2+1).noneMatch(i -> n % i == 0);
}
On earlier versions, this one should do the same work, 在较早的版本中,此功能应执行相同的工作,
String insertNum = JOptionPane.showInputDialog(null, "Insert a number\n");
int realNum = Integer.parseInt(insertNum);
boolean prime = true;
for (int i = 2; i <= realNum / 2; i++) {
if (realNum % i == 0) {
JOptionPane.showMessageDialog(null, "It is not a prime!!");
prime = false;
break;
}
}
if (prime) {
JOptionPane.showMessageDialog(null, "It is a prime!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.