Skip to content

Instantly share code, notes, and snippets.

@SeanTRobinson
Last active August 29, 2015 14:01
Show Gist options
  • Save SeanTRobinson/22de85b68258a3903198 to your computer and use it in GitHub Desktop.
Save SeanTRobinson/22de85b68258a3903198 to your computer and use it in GitHub Desktop.
A C# implementation of the Sieve of Eratosthenes algorithm.
namespace SieveOfEratosthenes
{
class SieveOfEratosphenes
{
public static void printPrimesUntil(int n)
{
List<int> primes = getPrimesUntil(n);
printList(primes);
}
private static List<int> getPrimesUntil(int n)
{
bool[] primes = initialiseArrayOfSize(n);
sieveNonPrimes(primes);
return listFromPrimesSieve(primes);
}
private static bool[] initialiseArrayOfSize(int n)
{
bool[] primes = new bool[n + 1];
for (int i = 0; i <= n; i++) { primes[i] = true; }
return primes;
}
private static void sieveNonPrimes(bool[] primes)
{
for (int i = 2; i < Math.Sqrt(primes.Length); i++)
{
for (int p = i+i; p < primes.Length; p += i)
{
primes[p] = false;
}
}
}
private static List<int> listFromPrimesSieve(bool[] primes)
{
List<int> primeList = new List<int>();
for(int i=1; i<primes.Length; i++)
{
if(primes[i])
{
primeList.Add(i);
}
}
return primeList;
}
private static void printList(List<int> primes)
{
foreach(int prime in primes)
{
Console.Write(prime + ", ");
}
Console.WriteLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment