求某個正整數範圍內的所有素數
阿新 • • 發佈:2019-01-10
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
int n = scan.nextInt();
List<Integer> primers = getPrimer(n);
System.out.println(primers); }
}
public static ArrayList<Integer> getPrimer(int n){
boolean[] isPrimer = new boolean[n+1];
ArrayList<Integer> primers = new ArrayList<Integer>();
if(n < 2) return primers;
for(int i = 0; i <=n; i++ ){
if(i%2 != 0) isPrimer[i] = true;
else isPrimer[i] = false; //偶數為false
}
//如果isPrimer[i]為true,即i為素數,那麼i,2*i,3*i。。。一定不是素數
for(int i = 2; i <= Math.sqrt(n); i++)
for(int j = i+i; j <= n; j+=i){
if(isPrimer[i])
isPrimer[j] = false;
}
primers.add(2 );
for(int i = 3; i <=n; i++){
if(isPrimer[i])
primers.add(i);
}
return primers;
}
}