简体   繁体   English

哪种Eratosthenes筛网实施效率更高?

[英]Which Sieve of Eratosthenes implementation is more efficient?

I have two implementations of the Sieve of Eratosthenes. 我有两种Eratosthenes筛子的实现。 Here's the first: 这是第一个:

public class SieveOfEratosthenes extends PrimeGenerator {

    private boolean[] sieve;
    private List<Integer> primes;

    public SieveOfEratosthenes(int depth) {
        super(depth);

        sieve = new boolean[depth + 1];
        primes = new ArrayList<>();

        generate();
    }

    private void setPrime(int n) {
        sieve[n] = true;
        primes.add(n);
    }

    private void generate() {
        setPrime(2);
        setPrime(3);

        for (int n = 4; n <= depth; n++) {
            boolean isPrime = true;

            for (int prime : primes) 
                if (n % prime == 0) 
                    isPrime = false;

            if (isPrime)
                setPrime(n);
        }
    }
}

And here's the second. 这是第二个。

public boolean[] sieve(int n)
{
   boolean[] prime=new boolean[n+1];
   Arrays.fill(prime,true);
   prime[0]=false;
   prime[1]=false;
   int m=Math.sqrt(n);

   for (int i=2; i<=m; i++)
      if (prime[i])
         for (int k=i*i; k<=n; k+=i)
            prime[k]=false;

   return prime;
} 

Obviously the second is less verbose. 显然,第二个则不那么冗长。 It's not meant to be part of a hierarchy of prime generators. 这并不是要成为主要生成器层次结构的一部分。 But my question is, which is more efficient? 但是我的问题是,哪个更有效? The first one seems to be O(N*log(N)) but I am not sure of that. 第一个似乎是O(N * log(N)),但我不确定。 I'm not sure what the growth rate would be of the second. 我不确定第二年的增长率是多少。

The second is more efficient. 第二个更有效率。 It is also the Sieve of Eratosthenes. 它也是Eratosthenes的筛子。 The first algorithm is trial division, and is not the Sieve of Eratosthenes. 第一种算法是试验分割,而不是 Eratosthenes筛。

The first algorithm has a time complexity of O( n sqrt( n )), or perhaps a bit less if you use only primes as trial divisors. 第一种算法的时间复杂度为O( n sqrt( n )),或者,如果仅使用质数作为试验除数,则可能会少一些。 The second algorithm has a time complexity of O( n log log n ), which is near-enough linear since log log n is very small. 第二种算法的时间复杂度为O( n log log n ),由于log log n非常小,因此几乎是线性的。

As an experiment, compute the first million primes, up to 15485863, and see which one is faster. 作为实验,计算前一百万个素数,直到15485863,然后看哪个更快。 It won't be even close. 它甚至不会接近。 The second algorithm will finish in a few seconds. 第二种算法将在几秒钟内完成。 The first algorithm will take a few hours. 第一个算法将花费几个小时。

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

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