Click here to Skip to main content
15,889,335 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.
4.00/5 (1 vote)
20 Sep 2011CPOL 14.1K   1
This solution uses half the space by simply ignoring all even numbers. It will require a little index calculation. Also, primes are generated one by one instead of returning a list.Another optimization can be made by starting the crossing out of multiples of a prime p at p2. Any smaller number...

This solution uses half the space by simply ignoring all even numbers. It will require a little index calculation. Also, primes are generated one by one instead of returning a list.


Another optimization can be made by starting the crossing out of multiples of a prime p at p2. Any smaller number will already have been crossed out. For the same reason, we can stop looking for non-primes at Sqrt(bound). (Any number greater than that will have been crossed out as a multiple of a smaller number.)


C#
public static IEnumerable<int> Primes(int bound)
{
    if (bound < 2) yield break;
    //The first prime number is 2
    yield return 2;

    //Create a sieve of 'half size' starting at 3
    BitArray notPrime = new BitArray((bound - 1) >> 1);
    int limit = ((int)(Math.Sqrt(bound)) - 1) >> 1;
    for (int i = 0; i < limit; i++) {
        if (notPrime[i]) continue;
        //The first number not crossed out is prime
        int prime = 2 * i + 3;
        yield return prime;
        //cross out all multiples of this prime, starting at the prime squared
        for (int j = (prime * prime - 2) >> 1; j < notPrime.Count; j += prime) {
            notPrime[j] = true;
        }
    }
    //The remaining numbers not crossed out are also prime
    for (int i = limit; i < notPrime.Count; i++) {
        if (!notPrime[i]) yield return 2 * i + 3;
    }
}

License

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


Written By
Software Developer (Junior)
Netherlands Netherlands
Software developer with a bachelor degree and a few years experience (studied computer science at a university as well, but didn't finish). Really love C#, but work usually involves Java. Some experience with VB and C as well.

When hobbying I almost exclusively use C# and AutoHotkey. In a previous life I did some Haskell and Modula-3 and similar stuff. I enjoy games and solving puzzles like on http://projecteuler.net/ (I think I'm stuck at level 4, though)

Comments and Discussions

 
Generalso simple and compact very nice .. Pin
Denno.Secqtinstien17-Nov-11 23:32
Denno.Secqtinstien17-Nov-11 23:32 

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.