qq_29901455 2019-03-14 19:52 采纳率: 60%
浏览 536
已采纳

一段关于Java打印素数的代码,看不懂,求解答!

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条回答

  • 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 + " "); //如果是素数,输出,并且加上一个空格
        }
      }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突