【问题标题】:Show certain amount of prime numbers显示一定数量的素数
【发布时间】:2015-10-14 09:16:25
【问题描述】:

我一直在编写一些 java 代码来显示素数。我已经让它显示了 0 到 100 之间的所有素数。

我将如何做到这一点,以便我可以将变量设置为 20,它会显示前 20 个素数。

我的代码:

public class PrimeNumber {

    /**
     * @param args the command line arguments
     */
 private static boolean prime = true;
 private static int count =  20;

    public static void main(String[] args) {

        for (int i = 2; i < 100; i++) {
            for (int j = 2; j < 100; j++) {
                if(i == j)
                {
                    continue;
                }
                if (i % j == 0) {
                    prime = false;
                    break;
                } else {
                    prime = true;
                }
            }
            if (prime) {
                System.out.println(i + " is a Prime:");
            }

        }

    }

}

【问题讨论】:

    标签: java arrays primes


    【解决方案1】:

    对于 OPs 代码,这是最简单的实现。

    减小count 变量并在外部for loop 中检查它,直到它达到zero。此外,内部 for 循环应该只检查到 (i/2 + 1) 的当前值。另一半你总是可以跳过,值将除以数字将是i本身。

    public class PrimeNumber {    
      /**
       * @param args the command line arguments
       */
      private static boolean prime = true;
      private static int count =  20;
    
      public static void main(String[] args) {
    
        for (int i = 2; count>0; i++) {
          for (int j = 2; j < i/2 + 1; j++) {
            if (i % j == 0) {
              prime = false;
              break;
            } else {
              prime = true;
            }
          }
          if (prime) {
            System.out.println(i + " is a Prime:");
            count--;
          }    
        }    
      }    
    }
    

    【讨论】:

      【解决方案2】:

      检查以下代码以获得答案:

      public class PrimeNumber {
      private static boolean prime = true;
      private static int count =  20;
      
          public static void main(String[] args) {
      
              for (int i = 2; i < count+1; i++) {
                  for (int j = 2; j < 100; j++) {
                      if(i == j)
                      {
                          continue;
                      }
                      if (i % j == 0) {
                          prime = false;
                          break;
                      } else {
                          prime = true;
                      }
                  }
                  if (prime) {
                      System.out.println(i + " is a Prime:");
                  }}}}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多