/*
** Project Name: PrimeTime
** Author: Robert Whitney <[email protected]>
** Description: Uses multi-threading to find prime numbers in generated chunks and then prints all primes to the screen.
** Processes about 873,190 numbers/second in blocks of 10,000 using 4 worker threads.
** Tested on Windows 8.1 x64, w/ Intel Core i7 2600 (3.40GHz) processor.
** Max integer limited to value of Int32.MaxValue (2,147,483,647)
*/
/* Include libraries for the project */
using System;
using System.Threading;
using System.Diagnostics;
namespace PrimeTime
{
class PrimeTime
{
static void Main(string[] args)
{
int i;
int initThreadCount = Process.GetCurrentProcess().Threads.Count;
bool num = int.TryParse(args[0], out i);
if( i < 0 )
{
Console.WriteLine("Starting point must be 0 or greater!");
}
while ( i <= Int32.MaxValue && i >= 0 )
{
if( Process.GetCurrentProcess().Threads.Count-initThreadCount <= 4 )
{
Thread t = new Thread(() => checkBlockForPrime(i, i + 9999));
t.Start();
if (Int32.MaxValue - 10000 <= i)
{
i = Int32.MaxValue - 10000;
}
else
{
if (i == Int32.MaxValue)
{
Console.WriteLine("I have reached the maximum value of an int.");
break;
}
else
{
i = i + 10000;
}
}
}
}
Console.WriteLine("Cannot process numbers larger than " + Int32.MaxValue + " and will not process numbers smaller than 0");
}
public static void checkBlockForPrime(int start, int end)
{
int i = start;
while( i <= end )
{
if (checkPrime(i) == true)
{
Console.WriteLine(i);
}
i = i + 1;
}
}
public static bool checkPrime(int num)
{
// Test whether the parameter is a prime number.
if ((num & 1) == 0)
{
if (num == 2)
{
return true;
}
else
{
return false;
}
}
for (int i = 3; (i * i) <= num; i += 2)
{
if ((num % i) == 0)
{
return false;
}
}
return true;
}
}
}
Comments