簡體   English   中英

如何進一步優化Eratosthenes的篩選

[英]How to optimize Sieve of Eratosthenes further

我正在解決Project Euler問題10,並且我能夠使用Sieve of Eratosthenes進行解決,但現在我想進一步優化代碼。

考慮到大於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;
    }
}

那么如何通過減少數量來優化我篩選的代碼呢? 例如,如果我的數字是5,那么10,15,20之類的數字已經被觸發,但是25例如不是這樣,是否只能通過25這樣的值?

Paul Pritchard在輪式篩網方面做了大量工作,將6k±1的想法擴展到更大的主輪。 谷歌為“pritchard輪篩”或看看我的博客開始。

當消除素數p的倍數時,您只需要從p * p開始。 由於它具有較小的素因子,因此已經消除了任何低於p的倍數。 這就是你對5和25的評論背后的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM