简体   繁体   English

Eratosthenes筛网Java

[英]Sieve of Eratosthenes Issue Java

I've got an issue with an assignment that I have requiring the use of arrays. 我遇到了需要使用数组的赋值问题。 I need to create the Sieve of Eratosthenes algorithm and print out all the prime numbers. 我需要创建Eratosthenes的Sieve算法并打印出所有质数。 I'm quite confused because as far as I can tell, my order of operations is correct. 我很困惑,因为据我所知,我的操作顺序是正确的。 Here is the code: 这是代码:

        //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;
            }
        }

I first set all the numbers in the array to true. 我首先将数组中的所有数字设置为true。 Then the second loop will start "x" at 2, then inside it is a nested loop that will multiply "x" by values of "n" and "n" will continue to increase as long as the product of that multiplication ("y") is below 1000. Once "y" reaches that maximum, "x" will go up one number and the process repeats until all non-prime numbers are set to false. 然后,第二个循环将从2开始以“ x”开头,然后是一个嵌套循环,它将“ x”乘以“ n”的值,并且只要该乘积(“ y” “)小于1000。一旦“ y”达到最大值,“ x”将增加一个数字,然后重复该过程,直到所有非质数均设置为false。

That was my logic when I made the code, but when I try to run it I get the "ArrayIndexOutOfBoundsException" error. 编写代码时,这是我的逻辑,但是当我尝试运行它时,出现“ ArrayIndexOutOfBoundsException”错误。 From what I can tell I set everything to stay below 1000 so it shouldn't be going over the array size. 据我所知,我将所有内容都设置为1000以下,因此不应超出数组大小。

I know its probably not the most efficient algorithm because as "x" increases it will go over numbers it already went over but it was the most simple one I could think of. 我知道它可能不是最有效的算法,因为随着“ x”的增加,它将遍历已经遍历的数字,但这是我能想到的最简单的算法。

Here: 这里:

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

you first check that y < 1000 , and then intialize and use it. 首先检查y < 1000然后初始化并使用它。 This is the wrong way around. 这是错误的方法。

Also, you can get away with running the above loop only when x is prime. 另外,仅当x为质数时,您才可以运行上述循环。 This won't affect correctness, but should make your code much faster. 这不会影响正确性,但是可以使您的代码更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM