使用篩法列印質數
阿新 • • 發佈:2018-11-23
public static void main(String[] args) { //範圍:2到多少 int maxfanwei = 20; boolean[] bolist = new boolean[maxfanwei+1]; for (int i = 2; i < bolist.length; i++) { boolean isnotsushu = bolist[i];//不是素數true,是素數false if(!isnotsushu){int xiabiao = i; //這個數的倍數設定為true while (true) { xiabiao+=i; if (xiabiao>=(maxfanwei+1)) { break;//超過範圍退出設定 } bolist[xiabiao] = true; } } }//列印質數 for (int i = 2; i < bolist.length; i++) { if (!bolist[i]) { System.out.println(i+" "); } } }