我有一个素数计划的代码:
class Test2 {
public static void main(String[] args) {
System.out.println("Prime numbers inbetween 2-100: ");
boolean isComposite = false;
for (int i = 2; i <= 100; i++) {
if ((i % 2) == 0) {
continue;
}
for (int k = 3; k < i; k++) {
if ((i % k) == 0) {
isComposite = true;
break;
}
}
if (!isComposite) {
System.out.println(i);
isComposite = false;
}
}//End for
}//End main()
}//End class
我的问题是,当我运行该代码时,我得到以下输出:
Prime numbers inbetween 2-100:
3
5
7
这么简单的代码,但我无法弄清楚它的错误!任何帮助将不胜感激。
另外,在Java中查找素数的最佳算法是什么?
答案 0 :(得分:4)
您忘记重置isComposite
,因此在检测到9为复合后,以下所有数字都被视为复合错误:
for (int i = 2; i <= 100; i++) {
isComposite = false; // add this
...
P.S,2也是您的代码遗漏的素数,因此您应该单独打印:
System.out.println(2);
boolean isComposite = false;
for (int i = 3; i <= 100; i++) {
isComposite = false;
if ((i % 2) == 0) {
continue;
}
for (int k = 3; k < i; k++) {
if ((i % k) == 0) {
isComposite = true;
break;
}
}
if (!isComposite) {
System.out.println(i);
isComposite = false;
}
}//End for
答案 1 :(得分:4)
您需要将循环中的标记isComposite
重置为:
for (int i = 2; i <= 100; i++) {
isComposite = false;
if ((i % 2) == 0) {
continue;
}
for (int k = 3; k < i; k++) {
if ((i % k) == 0) {
isComposite = true;
break;
}
}
if (!isComposite) {
System.out.println(i);
isComposite = false;
}
}
否则它将永远保持true
循环。现在打印出来:
Prime numbers inbetween 2-100:
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97