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 + " "); //如果是素数,输出,并且加上一个空格 } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 安装svn网络有问题怎么办
- ¥15 Python爬取指定微博话题下的内容,保存为txt
- ¥15 vue2登录调用后端接口如何实现
- ¥65 永磁型步进电机PID算法
- ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
- ¥88 找成都本地经验丰富懂小程序开发的技术大咖
- ¥15 如何处理复杂数据表格的除法运算
- ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
- ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
- ¥15 latex怎么处理论文引理引用参考文献