public class E04_FindPrimes {
public static void main(String[] args) {
int max = 100;
// Get the max value from the command line,
// if the argument has been provided:
if(args.length != 0)
max = Integer.parseInt(args[0]);
for(int i = 1; i < max; i++) {
boolean prime = true;
for(int j = 2; j < i; j++)
if(i % j == 0)
prime = false;
if(prime)
System.out.print(i + " ");
}
}
} /* Output:
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
*///:~
3 回答

慕村9548890
TA贡献1884条经验 获得超4个赞
首先1不是素数,这个程序有点问题
下面注释下:
public class E04_FindPrimes { public static void main(String[] args) { int max = 100; // Get the max value from the command line, // if the argument has been provided: if(args.length != 0) //如果有参数 max = Integer.parseInt(args[0]); //最大值从参数里设置,如果没有,默认100 for(int i = 1; i < max; i++) { //从1~max寻找,但是这里的1应该修改为2才对。 boolean prime = true; // 都不能整除,默认就是素数,所以一开始是true for(int j = 2; j < i; j++) //素数是除了自身和1,不能被别的数整除的数,所以这里从2~i-1逐一尝试,实际上尝试到i/2就可以了。 if(i % j == 0) //如果可以整除 prime = false; //不是素数,这里加上一个break跳出循环更好 if(prime) System.out.print(i + " "); //如果是素数,输出,并且加上一个空格 } }

慕莱坞森
TA贡献1810条经验 获得超4个赞
这个很简单啊,测试1到100(max的值为100)的数,首先第1个是1,就拿从2(1肯定能整除的所以从2开始)开始到它本身(即1)去除,如果有数能整除(即余数为0)就不是素数,prime为false,既然是false就不把这个数输出,如果没有被1和他本身之外的数整除(即是素数),
prime = false;这句就不被执行,下面的条件prime为true,输出这个数。
添加回答
举报
0/150
提交
取消