Created
December 1, 2021 13:39
-
-
Save sonnemaf/11e46c92f5ebf51680463ecec23f37e1 to your computer and use it in GitHub Desktop.
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 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