sieve of eratosthenes in csharp

Here's an implementation of Sieve of Eratosthenes algorithm in C#:

main.cs
public static List<int> GetPrimes(int n)
{
    bool[] isPrime = new bool[n + 1];

    for (int i = 2; i <= n; i++)
    {
        isPrime[i] = true;
    }

    for (int p = 2; p * p <= n; p++)
    {
        if (isPrime[p])
        {
            for (int i = p * p; i <= n; i += p)
            {
                isPrime[i] = false;
            }
        }
    }

    List<int> primes = new List<int>();

    for (int i = 2; i <= n; i++)
    {
        if (isPrime[i])
        {
            primes.Add(i);
        }
    }

    return primes;
}
540 chars
33 lines

The method GetPrimes(int n) returns a list of prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm. The algorithm starts by creating an array of boolean values isPrime where isPrime[i] indicates whether the number i is prime or not.

Initially, all values in the array are set to true (since all numbers are potentially prime). Then, for each prime number p less than or equal to the square root of n, it marks all multiples of p (greater than or equal to p*p and less than or equal to n) as composite (i.e. not prime).

After marking all composite numbers, it finally lists all the prime numbers by adding them to a list and returning it.

This implementation also optimizes the algorithm by starting the loop for composite marking at p*p instead of 2*p and incrementing by p. This skips all multiples of p less than p*p, which have already been marked as composite by previous prime numbers.

gistlibby LogSnag