我在下面编写了以下代码来查找第 n 个素数。这可以在时间复杂度上得到改善吗?
描述:
ArrayList arr 存储计算的素数。一旦 arr 达到大小“n”,循环退出,我们检索 ArrayList 中的第 n 个元素。在计算素数之前将数字 2 和 3 添加,并检查从 4 开始的每个数字是否为素数。
public void calcPrime(int inp) {
ArrayList<Integer> arr = new ArrayList<Integer>(); // stores prime numbers
// calculated so far
// add prime numbers 2 and 3 to prime array 'arr'
arr.add(2);
arr.add(3);
// check if number is prime starting from 4
int counter = 4;
// check if arr's size has reached inp which is 'n', if so terminate while loop
while(arr.size() <= inp) {
// dont check for prime if number is divisible by 2
if(counter % 2 != 0) {
// check if current number 'counter' is perfectly divisible from
// counter/2 to 3
int temp = counter/2;
while(temp >=3) {
if(counter % temp == 0)
break;
temp --;
}
if(temp <= 3) {
arr.add(counter);
}
}
counter++;
}
System.out.println("finish" +arr.get(inp));
}
}