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
*///:~

一段关于Java打印素数的代码,看不懂,求解答!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
- threenewbee 2019-03-15 00:14关注
首先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 + " "); //如果是素数,输出,并且加上一个空格 } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报