JAVA的程式碼問題??{找1~100的質數}
用"篩選法"寫一個求1~100之間的質數
所謂[篩選法]演算法如下:
(1)宣告一個有N 1個元素的 Boolean 陣列。
(2)將每個元素的值都設為trun。
(3)以2的倍數為索引碼,將索引碼所指的元素設為 false ;再以3的倍數 為索引碼,再重複同樣的動作,依此類推,一直到 N 為止。
(4)陣列中元素值為 true 的索引碼就是質數。
3 個解答
- 匿名使用者2 0 年前最佳解答
public class test {//使用篩選法求質數
public static void main(String[] args) {
int n=100;
boolean[] ifPrime=new boolean[n+1];//宣告一個有n+1個元素的Boolean陣列
for (int i=0;i<=n;i++){//將每個元素的值都設為trun
ifPrime[i]=true;
}
for(int j=2;j<=n;j++){
for(int k=2*j;k<=n;k++){//從每個數的二倍開始設定
if(k%j==0)ifPrime[k]=false;//將索引碼所指的元素設為false
}
}
for (int e=1;e<=n;e++){//印出陣列中元素值為true質數的索引碼
if(ifPrime[e]==true)System.out.print(e+" ");
}
}
}
- 匿名使用者2 0 年前
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, \73, 79, 83, 89, 97,
以質數定義
公式
public class test {//使用篩選法求質數
public static void main(String[] args)
int n=100;
boolean[] ifPrime=new boolean[n+1];//宣告一個有n+1個元素的Boolean陣列
for (int i=0;i<=n;i++){//將每個元素的值都設為trun
ifPrime[i]=true;
for(int j=2;j<=n;j++)
for(int k=2*j;k<=n;k++){//從每個數的二倍開始設定
if(k%j==0)ifPrime[k]=false;//將索引碼所指的元素設為false
for (int e=1;e<=n;e++){//印出陣列中元素值為true質數的索引碼
if(ifPrime[e]==true)System.out.print(e+" ");
參考資料: 我 - 2 0 年前
將
for(int k=2*j;k<=n;k++){//從每個數的二倍開始設定
if(k%j==0)ifPrime[k]=false;
改成
for(int k=j*j;k<=n;k+=i){//從每個數的二倍開始設定
ifPrime[k] = false;
會比較好。