C# 如何进一步优化埃拉斯托烯的筛选

C# 如何进一步优化埃拉斯托烯的筛选,c#,optimization,primes,sieve-of-eratosthenes,C#,Optimization,Primes,Sieve Of Eratosthenes,我当时正在解决Project Euler问题10,我可以使用Eratosthenes筛来解决这个问题,但现在我想进一步优化代码 考虑到所有大于3的素数都是6k+1或6k-1的形式,我只将数组中的那些值设置为true,但不是所有形式的数都是素数,因此我必须筛选这些值并删除非素数,我的代码如下: public static bool[] GeneratePrimes(int bound) { bool[] isPrime = new bool[bound];

我当时正在解决Project Euler问题10,我可以使用Eratosthenes筛来解决这个问题,但现在我想进一步优化代码

考虑到所有大于3的素数都是
6k+1
6k-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;
    }
}
publicstaticbool[]生成时间(int-bound)
{
bool[]isPrime=新bool[绑定];
isPrime[2]=真;
isPrime[3]=真;
//考虑到所有大于2和3的素数
//其形式为6k+1或6k-1
对于(int k=6;k对于(int i=3;i*iPaul Pritchard在车轮筛方面做了大量工作,将您的6k±1想法扩展到更大的主车轮。谷歌搜索“Pritchard车轮筛”或者开始吧。

当消除素数p的倍数时,你只需要从p*p开始。下面任何p的倍数都已经被消除了,因为它的素数因子更小。这就是你关于5和25的评论背后的原因。

将你范围内的所有数字都列在一个列表中。从列表中删除它们是你吗通读它们。你可以推广到更大的素数,例如,所有>5的素数都是30k+{1,7,11,13,17,19,23,29},所有>7的素数都是210k+形式{1、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67、71、73、79、83、89、97、101、103、107、109、113、121、127、131、137、139、143、149、151、157、163、167、169、173、179、181、187、191、193、197、199、209}等等。