Click here to Skip to main content
14,117,047 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

11.3K views
Posted 12 Sep 2011
Licenced CPOL

Find Prime Numbers in C# Using the Sieve of Eratosthenes

, 12 Sep 2011
Rate this:
Please Sign up or sign in to vote.
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);
}

License

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

Share

About the Author

Bill Anderson
Web Developer
United States United States
Developer

You may also be interested in...

Pro

Comments and Discussions

 
Generalvery very nicely interpreted .. Pin
Denno.Secqtinstien17-Nov-11 23:31
memberDenno.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
memberPravin 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190518.1 | Last Updated 12 Sep 2011
Article Copyright 2011 by Bill Anderson
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid