Skip to content

Instantly share code, notes, and snippets.

@sonnemaf
Last active January 17, 2020 14:44
Show Gist options
  • Save sonnemaf/c067ce351055e8f54a1ee3b779c44c74 to your computer and use it in GitHub Desktop.
Save sonnemaf/c067ce351055e8f54a1ee3b779c44c74 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp39 {
class Program {
static void Main(string[] args) {
int total = 0;
var sw = Stopwatch.StartNew();
Parallel.For(1, 80_000_001,
() => 0,
(i, loopstate, local) => {
if (Utils.IsPrime(i)) {
local++;
}
return local;
},
local => Interlocked.Add(ref total, local)
);
sw.Stop();
Console.WriteLine($"{sw.Elapsed} {total}");
}
}
internal static class Utils {
public static int CountPrimes(int from, int to) {
int count = 0;
for (int i = from; i <= to; i++) {
if (IsPrime(i)) count++;
}
return count;
}
public static bool IsPrime(this int value) {
if (value > 1) {
//if ((value % 2) == 0) return value == 2;
if ((value & 1) == 0) return value == 2;
int sqrt = (int)Math.Sqrt(value);
for (int t = 3; t <= sqrt; t = t + 2) {
if (value % t == 0) {
return false;
}
}
return true;
}
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment