65.9K
CodeProject is changing. Read more.
Home

Find Prime Numbers in C# Using the Sieve of Eratosthenes

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Sep 12, 2011

CPOL
viewsIcon

17513

Here's an alternative. This one uses the BitArray class in C# and does not use the % operator.static List SeiveWithoutMod(int candidate){ BitArray sieveContainer = new BitArray(candidate + 1, true); int marker = 2; //start int factor = 2; //start. sieveContainer[0]...

Here's an alternative. This one uses the BitArray class in C# and does not use the % operator.

static List<int> SeiveWithoutMod(int candidate)
{
    BitArray sieveContainer = new BitArray(candidate + 1, true);
    int marker = 2; //start
    int factor = 2; //start.

    sieveContainer[0] = false;//0 is not prime
    sieveContainer[1] = false;//1 is not prime

    while ((marker * marker) <= sieveContainer.Length)
    {
        while ((factor += marker) <= candidate)
        {
            sieveContainer[factor] = false;
        };
        factor = ++marker; //reset
    }

    //Return only the "true" indexes
    return GetPrimes(sieveContainer);
}