StackOverflowError eratosthenes筛网实现

时间:2018-09-16 15:22:52

标签: java stack-overflow

我试图用Java实现Eratosthenes筛子,但是我有一个StackOverflowError像这样:

public function myFunction ($product){
    if (is_object($product)) {
        echo $product->getColor();
    } else {
        # catch the error / fault
    }
}

似乎像它的无限递归,但是算法在Exception in thread "main" java.lang.StackOverflowError at com.company.era2.sieve(era2.java:24) at com.company.era2.sieve(era2.java:24) at com.company.era2.sieve(era2.java:24) 下可以正常工作
我该怎么办? 代码:

n <= 90000

1 个答案:

答案 0 :(得分:0)

如果您不一定需要使用递归,这是受this wikipedia article启发的解决方案

public static List<Integer> sieve(int limit) {
    boolean[] array = new boolean[limit - 2];
    Arrays.fill(array, true);
    int end = (int)Math.sqrt(limit);

    for (int i = 2; i <= end; i++) {
        if (array[i - 2]) {
            int j = i * i;
            int k = 0;
            while (j < limit) {
                array[j - 2] = false;
                j = i * i + i * ++k;
            }
        }
    }

    List<Integer> result = new ArrayList<>();
    for (int l = 2; l < limit; l++) {
        if (array[l - 2]) {
            result.add(l);
        }
    }

    return result;
}