代碼如下:
/**
* @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);
}
}