获取指定数量素数.

时间:2021-04-29 10:39:49
import static java.lang.Math.ceil;
import static java.lang.Math.sqrt;

public class GetPrimes{

public static void main(String[] args){
long[] primes = getPrimes(100);
for(long prime : primes){
System.out.println(prime);
}
}

private static long[] getPrimes(int count){
assert count >= 2;
long[] primes = new long[count];
primes[0] = 2;
primes[1] = 3;

for(int i = 2 ; i < count ; i ++){
//这层循环用来计算素数的个数.

long num = primes[i - 1] + 2;
int j = 0;
long limit = (long)ceil(sqrt(num));

for(;(j < i) && (primes[j] < limit);){
//这层循环用来判断一个数是否是素数.
if(num % primes[j] == 0L){
num = num + 2;
//素数必为奇数,2除外.
j = 0;
limit = (long)ceil(sqrt(num));
//由于非素数是两个数相乘的结果,所以这里只要取值判断上限设置为平方根+1即可.
continue;
}
j ++;
}
primes[i] = num;
}
return primes;
}


}