Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created July 2, 2013 18:44
Show Gist options
  • Select an option

  • Save riyadparvez/5911941 to your computer and use it in GitHub Desktop.

Select an option

Save riyadparvez/5911941 to your computer and use it in GitHub Desktop.
Finds all the prime numbers up to n using Sieve of Eratosthenes in C#. See http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
public static IList<int> SieveOfEratosthenes(int n)
{
if(n < 2)
{
throw new ArgumentOutOfRangeException();
}
var arr = Enumerable.Repeat(true, n+1).ToArray();
for (int i = 2; i <= n; i++)
{
if(arr[i])
{
int j = 2;
int mul = 0;
while((mul = (j*i)) <= n)
{
arr[mul] = false;
j++;
}
}
}
var primes = new List<int>();
for (int i=2; i <= n; i++)
{
if(arr[i])
{
primes.Add(i);
}
}
return primes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment