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 + " "); //如果是素数,输出,并且加上一个空格 } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥50 有数据,怎么建立模型求影响全要素生产率的因素
- ¥50 有数据,怎么用matlab求全要素生产率
- ¥15 TI的insta-spin例程
- ¥15 完成下列问题完成下列问题
- ¥15 C#算法问题, 不知道怎么处理这个数据的转换
- ¥15 YoloV5 第三方库的版本对照问题
- ¥15 请完成下列相关问题!
- ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
- ¥15 求daily translation(DT)偏差订正方法的代码
- ¥15 js调用html页面需要隐藏某个按钮