12,454,477 members (56,857 online)
Alternative Tip/Trick
alternative version

4.1K views
Posted

# Find Prime Numbers in C# Using the Sieve of Eratosthenes

, 12 Sep 2011 CPOL
 Rate this:
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.

```static List<int> GetPrimeNumbers(int n)
{
bool[] notPrime = new bool[n + 1];
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)
{
}
}
}```

## Share

 Student Wales
No Biography provided

## You may also be interested in...

 Pro Pro

 First Prev Next
 I don't like this alternative because first of all it's a tr... Brian C Hart12-Sep-11 8:32 Brian C Hart 12-Sep-11 8:32
 Last Visit: 31-Dec-99 18:00     Last Update: 29-Aug-16 19:13 Refresh 1