-
-
Save ayende/563e0e4b0dae1bf986a660076f143aa6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System.Diagnostics; | |
var nums = Enumerable.Range(0, 100_000).Select(_ => Random.Shared.Next()).ToArray(); | |
for (int i = 0; i < 3; i++) | |
{ | |
{ | |
var total = Stopwatch.StartNew(); | |
var countPrimes = 0; | |
Stopwatch countTime = new(); | |
foreach (var num in nums) | |
{ | |
countTime.Start(); | |
if (IsPrime(num)) | |
countPrimes++; | |
countTime.Stop(); | |
} | |
Console.WriteLine(countPrimes + " in " + total.ElapsedMilliseconds + " without " + countTime.ElapsedMilliseconds); | |
} | |
{ | |
var total = Stopwatch.StartNew(); | |
var countPrimes = 0; | |
foreach (var num in nums) | |
{ | |
if (IsPrime(num)) | |
countPrimes++; | |
} | |
Console.WriteLine(countPrimes + " in " + total.ElapsedMilliseconds); | |
} | |
} | |
bool IsPrime(int n) | |
{ | |
if (n == 1) | |
{ | |
return false; | |
} | |
int i = 2; | |
while (i * i <= n) | |
{ | |
if (n % i == 0) | |
{ | |
return false; | |
} | |
i += 1; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment