Java打印素數(質數)

要求:打印 2 - 100000 當中的素數與非素數。(素數定義:在大於1的天然數中,除了1和它自己之外再也不有其餘因數)數組

1. 常規方式——對正整數n,若是用2到  之間的全部整數去除,均沒法整除,則n爲質數:性能

  // sqrt 法
  public static void printPrime1(int num) {
    boolean[] isPrimes = new boolean[num + 1];
    for (int i = 2; i < isPrimes.length; i++) {
      isPrimes[i] = true;
    }

    for (int i = 3; i <= num; i++) {
      for (int j = 2; j <= Math.sqrt(i); j++) {
        if (i % j == 0) {
          isPrimes[i] = false;
          break;
        }
      }
    }

    System.out.print("質數有: ");
    for (int i = 2; i < isPrimes.length; i++) {
      if (isPrimes[i]) {
        System.out.print(i + " ");
      }
    }
    System.out.println("");
    System.out.print("非質數有: ");
    for (int i = 2; i < isPrimes.length; i++) {
      if (!isPrimes[i]) {
        System.out.print(i + " ");
      }
    }
  }

  注意這裏用一個布爾類型的數組用於素數的判斷與最終結果的打印,避免了使用兩個容器去分別存放各自須要打印的兩塊內容。spa

 2. 埃氏篩選法code

  // 埃氏篩法
  public static void printPrime2(int num) {
    boolean[] isPrimes = new boolean[num + 1];
    for (int i = 2; i < isPrimes.length; i++) {
      isPrimes[i] = true;
    }
    for (int i = 2; i <= Math.sqrt(num); i++) {
      if (isPrimes[i] == true) {
        for (int j = 2; i * j <= num; j++) {
          isPrimes[i * j] = false;
        }
      }
    }

    System.out.print("質數有: ");
    for (int i = 2; i < isPrimes.length; i++) {
      if (isPrimes[i]) {
        System.out.print(i + " ");
      }
    }
    System.out.println("");
    System.out.print("非質數有: ");
    for (int i = 2; i < isPrimes.length; i++) {
      if (!isPrimes[i]) {
        System.out.print(i + " ");
      }
    }
  }

  最後提供一個main方法,完成對兩個方法的調用與性能比較:blog

  public static void main(String[] args) {
    long timePoint1 = System.currentTimeMillis();
    printPrime1(100000);
    long timePoint2 = System.currentTimeMillis();
    System.out.println();
    printPrime2(100000);
    long timePoint3 = System.currentTimeMillis();

    System.out.println();
    System.out.println("sqrt法耗時: " + String.valueOf(timePoint2 - timePoint1)); // 390 ms
    System.out.println("埃氏篩法耗時: " + String.valueOf(timePoint3 - timePoint2)); // 297 ms
  }
相關文章
相關標籤/搜索