java使用篩選法求n以內的素數示例(java求素數)
更新時間:2014年04月16日 09:44:55 作者:
這篇文章主要介紹了java使用篩選法求n以內的素數示例(java求素數),需要的朋友可以參考下
復制代碼 代碼如下:
/**
* @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);
}
}
相關文章
Springboot多環(huán)境開發(fā)及使用方法
這篇文章主要介紹了Springboot多環(huán)境開發(fā)及多環(huán)境設置使用、多環(huán)境分組管理的相關知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
MybatisPlus實現分頁查詢和動態(tài)SQL查詢的示例代碼
本文主要介紹了MybatisPlus實現分頁查詢和動態(tài)SQL查詢的示例代碼,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09

