简体   繁体   English

埃拉托色尼筛,生成素数。 循环问题

[英]Sieve of Eratosthenes, generating primes. Problem with loops

I'm trying to generate n number of primes using the Sieve of Eratosthenes algorithm.我正在尝试使用 Eratosthenes 筛算法生成 n 个素数。 I debugged it and saw that at some point it starts deleting numbers that had already been deleted.我调试了它,看到它在某个时候开始删除已经删除的数字。 I can't what's the problem, but I can bet it's to do with my loops.我不知道是什么问题,但我敢打赌这与我的循环有关。 Could you help pls?你能帮忙吗?

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Part6 {

    public static List<Integer> primeSequence(int n) {
        List<Integer> list = IntStream.range(2, n).boxed().collect(Collectors.toList());

        for (int i = 2; i <= list.size(); i++) {
            for (int j = i + 1; j <= list.size(); j++) {
            if(j % i == 0)
                list.remove(j);
            }
        }
       return  list;
        }


    public static void main(String[] args) {
        System.out.println(primeSequence(Integer.parseInt(args[0])));
    }
    
}

This is how Sieve of Eratosthenes works, it keeps marking all the multiples of prime numbers other than itself in the range.这就是Eratosthenes 筛法的工作原理,它不断标记范围内除自身以外的所有prime数的倍数。
For example, when we start with i=2 , we marks 4, 6, 8, 10, 12, ... as composite number.例如,当我们以i=2开始时,我们将4, 6, 8, 10, 12, ...标记为composite数。
Again for i=3 , it will mark 6, 9, 12, 15, ... as non-prime.同样对于i=3 ,它会将6, 9, 12, 15, ...标记为非质数。
Please observe that 6 & 12 were marked twice.请注意612被标记了两次。 There are many more numbers which would be marked as composites multiple times.还有更多的数字将被多次标记为复合。 Hence this is normal.因此这是正常的。

Now, the above program has many issues as:现在,上面的程序有很多问题:

  1. When you perform list.remove(j) , it actually removes the number at index j not the number j itself.当您执行list.remove(j) ,它实际上删除了索引j的数字而不是数字j本身。 So, to remove the composite number j we need to use Integer.valueOf(j)因此,要删除合数j我们需要使用Integer.valueOf(j)
  2. Upper limit of the loops should not be list.size() as the size of list will keep decreasing as we keep removing the numbers.循环的上限不应该是list.size()因为列表的大小会随着我们不断删除数字而不断减小。 Hence, many numbers will be missed.因此,许多数字将被遗漏。

Below is the modified version of your code:以下是您的代码的修改版本:

        for (int i = 2; i < n; i++)
        {
            for (int j = i + 1; j <= n; j++)
            {
                if (j % i == 0)
                {
                    list.remove(Integer.valueOf(j));
                }
            }
            System.out.println(list);
        }

Input: 100输入: 100
Output:输出:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

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

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