Created
April 8, 2016 01:57
-
-
Save kasecato/7bca3fb42dd9486cfe076871dba02182 to your computer and use it in GitHub Desktop.
ParallelTest C#
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; | |
using System.Linq; | |
using System.Diagnostics; | |
namespace ParallelTest | |
{ | |
public class Program | |
{ | |
public static void Main() | |
{ | |
const int max = 10000000; | |
var startTime = Stopwatch.StartNew(); | |
var pt = new Program(); | |
int primes = pt.countPrimes(max); | |
Console.WriteLine(primes); | |
startTime.Stop(); | |
Console.WriteLine(startTime.Elapsed.TotalMilliseconds.ToString()); | |
} | |
private int countPrimes(int max) | |
{ | |
return Enumerable | |
.Range(1, max) | |
.AsParallel() | |
.Where(x => isPrime(x)) | |
.Count(); | |
} | |
private bool isPrime(long n) | |
{ | |
if (n < 2) return false; | |
if (n == 2 || n == 3) return true; | |
if (n % 2 == 0 || n % 3 == 0) return false; | |
long sqrtN = (long)Math.Sqrt(n) + 1; | |
for (long i = 6L; i <= sqrtN; i += 6) | |
{ | |
if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment