简体   繁体   English

如何进一步优化Eratosthenes的筛选

[英]How to optimize Sieve of Eratosthenes further

I was solving Project Euler problem 10 and I was able to do so using the Sieve of Eratosthenes, but now I'd like to optimize the code a bit further. 我正在解决Project Euler问题10,并且我能够使用Sieve of Eratosthenes进行解决,但现在我想进一步优化代码。

Considering the fact that all prime numbers greater than 3 are of the form 6k+1 or 6k-1 I only set those values in the array as true, but not all numbers of that form will be prime, so I have to sieve through the values and remove the non primes, and my code is as follows: 考虑到大于3的所有素数都是6k+16k-1我只将数组中的那些值设置为true,但不是所有形式的数字都是素数,所以我必须筛选值并删除非素数,我的代码如下:

public static bool[] GeneratePrimes(int bound)
    {
        bool[] isPrime = new bool[bound];
        isPrime[2] = true;
        isPrime[3] = true;

        // Taking into account that all primes greater than 2 and 3
        // Are of the form 6k+1 or 6k-1

        for (int k = 6; k < isPrime.Length; k += 6)
        {
            if (k + 1 < isPrime.Length) isPrime[k + 1] = true;
            isPrime[k - 1] = true;
        }

        // At this point we still have some numbers that aren't prime marked as prime
        // So we go over them with a sieve, also we can start at 3 for obvious reasons

        for (int i = 3; i * i <= bound; i += 2)
        {
            if (isPrime[i])
            {
                // Can this be optimized?
                for (int j = i; j * i <= bound; j++)
                    isPrime[i * j] = false;
            }
        }

        return isPrime;
    }
}

So how can I optimize the code that I sieve through less numbers? 那么如何通过减少数量来优化我筛选的代码呢? For example if my number is 5, numbers such as 10,15,20 are already stroked through, but 25 for example isn't so is it possible to only go through values such is 25? 例如,如果我的数字是5,那么10,15,20之类的数字已经被触发,但是25例如不是这样,是否只能通过25这样的值?

Paul Pritchard has done much work with wheel sieves that extend your 6k±1 idea to larger prime wheels. Paul Pritchard在轮式筛网方面做了大量工作,将6k±1的想法扩展到更大的主轮。 Google for "pritchard wheel sieve" or look at my blog to get started. 谷歌为“pritchard轮筛”或看看我的博客开始。

When eliminating multiples of a prime p, you only need to start from p * p. 当消除素数p的倍数时,您只需要从p * p开始。 Any multiple of p below that will already have been eliminated as it has a smaller prime factor. 由于它具有较小的素因子,因此已经消除了任何低于p的倍数。 This is the reason behind your comments about 5 and 25. 这就是你对5和25的评论背后的原因。

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

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