Click here to Skip to main content
15,848,724 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.
0.00/5 (No votes)
12 Sep 2011CPOL 9K   1
The following method starts by selecting the number 2 and eliminates each multiple of 2 up to N. Then the next valid number is selected and each multiple of it is eliminated. The process is repeated until all valid numbers have been tested. So the first three multiples to be eliminated are...

The following method starts by selecting the number 2 and eliminates each multiple of 2 up to N. Then the next valid number is selected and each multiple of it is eliminated. The process is repeated until all valid numbers have been tested. So the first three multiples to be eliminated are those of 2, 3, and 5. The number 4 is skipped as it has already been eliminated because it’s a multiple of 2. A number is eliminated by simply setting the appropriate member of a Boolean array.


C#
static List<int> GetPrimeNumbers(int n)
{
    bool[] notPrime = new bool[n + 1];
    List<int> primeNumbers = new List<int>();
    for (int i = 2; i <= n; i++)
    {
        if (notPrime[i] == false)
        {
            int m;
            int multiplicand = 2;
            while (( m = multiplicand * i) <= n)
            {
                notPrime[m] = true;
                multiplicand++;
            }
        }
    }
    for (int i = 2; i <= n; i++)
    {
        if (notPrime[i] == false)
        {
            primeNumbers.Add(i);
        }
    }
    return primeNumbers;
}

License

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


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralI don't like this alternative because first of all it's a tr... Pin
Brian C Hart12-Sep-11 9:32
professionalBrian C Hart12-Sep-11 9:32 
I don't like this alternative because first of all it's a trivial duplication of the Sieve (i.e., it's what the Sieve does in the first place) and it's not optimized because it uses two lists of size N instead of just one. Not a big deal when N is a small number, but what if I put in something closesest to the largest int (65536)? Then I'm allocating initial storage for 130,000 items and I then prune the storage down. And then I have 130,000 iterations (two for loops of N iterations each -- it's really N-2 iterations but I'm talking in the large-N limit.

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.