Eratosthenes Sieve问题Java

时间:2013-03-06 14:51:53

标签: java sieve-of-eratosthenes

我遇到了一个需要使用数组的赋值问题。我需要创建Sierat of Eratosthenes算法并打印出所有素数。我很困惑,因为据我所知,我的操作顺序是正确的。这是代码:

        //Declare the array
        boolean numbers [] = new boolean[1000];
        int y = 0;

        //Declare all numbers as true to begin
        for(int i = 2; i < 1000;i++){
            numbers[i] = true;
        }
        //Run loop that increases i and multiplies it by increasing multiples
        for (int x = 2; x < 1000; x++) {

            //A loop for the increasing multiples; keep those numbers below 1000
            //Set any multiple of "x" to false
            for(int n = 2; y < 1000; n++){
            y = n * x;
            numbers[y] = false;
            }
        }

我首先将数组中的所有数字设置为true。然后第二个循环将在2处开始“x”,然后在它内部是一个嵌套循环,它将“x”乘以“n”的值,并且“n”将继续增加,只要该乘法的乘积(“y” “)低于1000.一旦”y“达到最大值,”x“将上升一个数字并重复该过程,直到所有非素数都设置为假。

这是我编写代码时的逻辑,但是当我尝试运行它时,我得到“ArrayIndexOutOfBoundsException”错误。据我所知,我将所有内容设置为低于1000,因此它不应超过数组大小。

我知道它可能不是最有效的算法,因为当“x”增加它会超过它已经过去的数字,但它是我能想到的最简单的算法。

1 个答案:

答案 0 :(得分:4)

下面:

        for(int n = 2; y < 1000; n++){
        y = n * x;
        numbers[y] = false;
        }

首先检查y < 1000然后初始化并使用它。这是错误的方法。

此外,只有在x为素数时才能运行上述循环。这不会影响正确性,但应该使代码更快。