Created
April 2, 2024 18:09
-
-
Save mrange/83a4b18c9975942d818bdf083144547c to your computer and use it in GitHub Desktop.
Sieve Of Eratosthenes (C#)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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