Untitled

mail@pastecode.io avatar
unknown
csharp
a year ago
1.2 kB
0
Indexable
Never
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

class Program {
    static void Main(string[] args) {
        int startNumber = 1;
        int endNumber = 1000000;
        int maxThreads = Environment.ProcessorCount;

        ConcurrentBag<int> primes = new ConcurrentBag<int>();
        Parallel.For(startNumber, endNumber + 1, new ParallelOptions { MaxDegreeOfParallelism = maxThreads }, i => {
            if (IsPrime(i)) {
                primes.Add(i);
            }
        });

        Console.WriteLine("Found " + primes.Count + " prime numbers between " + startNumber + " and " + endNumber + ".");
        Console.ReadLine();
    }

    static bool IsPrime(int number) {
        if (number < 2) {
            return false;
        }
        if (number == 2 || number == 3) {
            return true;
        }
        if (number % 2 == 0 || number % 3 == 0) {
            return false;
        }
        int i = 5;
        int w = 2;
        while (i * i <= number) {
            if (number % i == 0) {
                return false;
            }
            i += w;
            w = 6 - w;
        }
        return true;
    }
}