Click here to Skip to main content
15,881,027 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Find Prime Numbers in C# Using the Sieve of Eratosthenes

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
12 Sep 2011CPOL 15.8K   5
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.


C#
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Developer

Comments and Discussions

 
Generalvery very nicely interpreted .. Pin
Denno.Secqtinstien17-Nov-11 23:31
Denno.Secqtinstien17-Nov-11 23:31 
GeneralReason for my vote of 5 Very Good - Well thought out! Pin
Dave Vroman11-Oct-11 19:34
professionalDave Vroman11-Oct-11 19:34 
GeneralNice and clean, but still room for improvement. There's no n... Pin
Jürgen Röhr21-Sep-11 21:15
professionalJürgen Röhr21-Sep-11 21:15 
GeneralReason for my vote of 5 Good alternative Pin
Pravin Patil, Mumbai12-Sep-11 8:20
Pravin Patil, Mumbai12-Sep-11 8:20 
GeneralInteresting application of BitArray. Pin
Dr.Walt Fair, PE11-Sep-11 15:06
professionalDr.Walt Fair, PE11-Sep-11 15:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.