Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Find Prime Numbers in C# Using the Sieve of Eratosthenes

, 12 Sep 2011 CPOL
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

Comments and Discussions

 
Generalvery very nicely interpreted .. Pinmemberdineshkummarc18-Nov-11 0:31 
GeneralReason for my vote of 5 Very Good - Well thought out! PinmemberDave Vroman11-Oct-11 20:34 
GeneralNice and clean, but still room for improvement. There's no n... PinmemberJürgen Röhr21-Sep-11 22:15 
GeneralReason for my vote of 5 Good alternative PinmemberPravin Patil, Mumbai12-Sep-11 9:20 
GeneralInteresting application of BitArray. PinsubeditorWalt Fair, Jr.11-Sep-11 16:06 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 12 Sep 2011
Article Copyright 2011 by Bill Anderson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid