Skip to content

Instantly share code, notes, and snippets.

@mrange
Created April 2, 2024 18:09
Show Gist options
  • Save mrange/83a4b18c9975942d818bdf083144547c to your computer and use it in GitHub Desktop.
Save mrange/83a4b18c9975942d818bdf083144547c to your computer and use it in GitHub Desktop.
Sieve Of Eratosthenes (C#)
var primes = SieveOfEratosthenes(100);
var primes_ = string.Join(',', primes);
Console.WriteLine(primes_);
int[] SieveOfEratosthenes(int n)
{
bool[] noPrime = new bool[n];
for (int p = 2; p * p < noPrime.Length; ++p)
{
if (!noPrime[p])
{
for (int i = 2*p; i < noPrime.Length; i += p)
{
noPrime[i] = true;
}
}
}
var result = new List<int>(noPrime.Length);
for (var i = 2; i < noPrime.Length; ++i)
{
if (!noPrime[i])
{
result.Add(i);
}
}
return result.ToArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment