/**
* @author jxqlovedn
* 埃拉托斯特尼素數(shù)篩選法,請參考:http://zh.wikipedia.org/zh-cn/埃拉托斯特尼篩法
*/
public class AratosternyAlgorithm {
public static void getPrimes(int n) {
if(n < 2 || n > 1000000) // 之所以限制最大值為100萬,是因為JVM內(nèi)存限制,當(dāng)然有其他靈活方案可以繞過(比如位圖法)
throw new IllegalArgumentException("輸入?yún)?shù)n錯誤!");
int[] array = new int[n]; // 假設(shè)初始所有數(shù)都是素數(shù),且某個數(shù)是素數(shù),則其值為0;比如第一個數(shù)為素數(shù)那么array[0]為0
array[0] = 1; // 0不是素數(shù)
array[1] = 1; // 1不是素數(shù)
// 下面是篩選核心過程
for(int i = 2; i < Math.sqrt(n);i++) { // 從最小素數(shù)2開始
if(array[i] == 0) {
for(int j = i*i; j < n; j += i) {
array[j] = 1; // 標(biāo)識該位置為非素數(shù)
}
}
}
// 打印n以內(nèi)的所有素數(shù),每排10個輸出
System.out.println(n + "以內(nèi)的素數(shù)如下: ");
int count = 0; // 當(dāng)前已經(jīng)輸出的素數(shù)個數(shù)
int rowLength = 10; // 每行輸出的素數(shù)個數(shù)
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);
}
}