Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Created December 1, 2021 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sonnemaf/11e46c92f5ebf51680463ecec23f37e1 to your computer and use it in GitHub Desktop.
Save sonnemaf/11e46c92f5ebf51680463ecec23f37e1 to your computer and use it in GitHub Desktop.
var sw = System.Diagnostics.Stopwatch.StartNew();
int total = 0;
for (int i = 1; i <= 20_000_000; i++) {
if (IsPrime(i)) {
total++;
}
}
sw.Stop();
Console.WriteLine($"{total} in {sw.Elapsed} sec");
bool IsPrime(int number) {
if ((number % 2) == 0) {
return number == 2;
}
var sqrt = (int)Math.Sqrt(number);
for (int t = 3; t <= sqrt; t += 2) {
if ((number % t) == 0) {
return false;
}
}
return number > 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment