java使用篩選法求n以內的素數樣本(java求素數)_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

/**
 * @author jxqlovedn
 * 埃拉托斯特尼素數篩選法,請參考:http://zh.wikipedia.org/zh-cn/埃拉托斯特尼篩法
 */
public class AratosternyAlgorithm {

 public static void getPrimes(int n) {
  if(n < 2 || n > 1000000)   // 之所以限制最大值為100萬,是因為JVM記憶體限制,當然有其他靈活方案可以繞過(比如位元影像法)
   throw new IllegalArgumentException("輸入參數n錯誤!");

  int[] array = new int[n];   // 假設初始所有數都是素數,且某個數是素數,則其值為0;比如第一個數為素數那麼array[0]為0
  array[0] = 1;   // 0不是素數
  array[1] = 1;   // 1不是素數
  // 下面是篩選核心過程
  for(int i = 2; i < Math.sqrt(n);i++) {   // 從最小素數2開始
   if(array[i] == 0) {
    for(int j = i*i; j < n; j += i) {
     array[j] = 1;   // 標識該位置為非素數
    }
   }
  }

  // 列印n以內的所有素數,每排10個輸出
  System.out.println(n + "以內的素數如下: ");
  int count = 0;        // 當前已經輸出的素數個數
  int rowLength = 10;   // 每行輸出的素數個數
  for(int i = 0; i < array.length; i++) {
   if(array[i] == 0) {
    if(count % rowLength == 0 && count != 0) {
     System.out.println();
    }
    count++;

    System.out.print(i + "\t");
   }
  }
 }

 public static void main(String[] args) {
  getPrimes(99999);
 }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.