Here's an implementation of Sieve of Eratosthenes algorithm in C#:
main.cs540 chars33 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