我正在尝试在 Java 中创建一个 Eratosthenes 筛,但我编写的代码似乎有缺陷。我想知道是否有其他人可以发现我的错误,因为我不能。我得到的输出只是 [2],这意味着我的主循环不起作用。我刚刚开始使用Java,如果您能给出详细的答案,我将不胜感激。
我的代码:
public static int[] primes(int n)
{
//Variable assignement
double sqrt;
List<Integer> primes= new ArrayList<Integer>();
//Adds 2 to primes so i don't need to include the even numbers in my for loop.
if(n>1)
{
primes.add(2);
}
//For loop that goes through the oneven numbers up to n
for(int counter1=3;counter1<=n;counter1+=2)
{
sqrt=Math.floor(Math.sqrt(0.0+counter1));
//for loop that tests if the first for loops number is prime
for(int counter2=0;sqrt<=primes.get(counter2);counter2++)
{
if(counter1 % primes.get(counter2) != 0 && counter2 ==sqrt)
{
primes.add(counter1);
}
if(counter1 % primes.get(counter2)==0)
{
break;
}
}
}
return convertIntegers(primes);
}
//Converts the list to an array
public static int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}