MTSkull
Centurion
I like to try programming challenges to keep the skills up and the mind sharp. One I tried recently was coding a prime number generator in C#. It works well and timing with a basic Tickcount timer it will generate primes to 1000 in about 16 milliseconds. 10000 in 125 milliseconds and 100000 in 10047 milliseconds (on my slowly helpful machine). Since the algorithm uses 2 for loops the execution time is a logarithmic function, if I remember right from algorithm theory. So here is what I came up with as the fastest method I could devise. Any tips to try and make it faster. I tried it up to 1000000 and broke execution since I got tired of waiting.
C#:
static void Main(string[] args)
{
//Console Shell to mess around in
Program pMain = new Program();
//Basic: Count File lines in a given text file at the root of c
//pMain.File_LineCount(args);
//Basic: Permute a string (not working correctly)
//pMain.Permutations(pMain, args);
//Int: Dec to Bin(string)
//pMain.DecToBinary();
//Int: Primes
pMain.Primes(pMain, args);
}
#region Primes
public void Primes(Program pMain, string[] args)
{
string UserInput = "";
Int64 Num = 0;
string Result = "";
int Start = 0;
int Stop = 0;
while (UserInput != "Q")
{
Console.WriteLine();
Console.WriteLine("Input a number to find Primes or Q to quit: ");
UserInput = Console.ReadLine();
if (UserInput.ToUpper() != "Q")
{
Start = Environment.TickCount;
Num = Convert.ToInt64(UserInput);
for (Int64 x = 2; x <= Num; x++)
{
if (TestBrute(x) == false)
{
Result = Result + "," + x.ToString();
}
}//end for
Stop = Environment.TickCount;
}//end user input if
Console.WriteLine(Result);
Console.WriteLine(Convert.ToString(Stop-Start));
}//end while
}
public bool TestBrute(Int64 Num)
{
Int64 Half = Num / 2;
if (Num == 2 || Num == 3)
return false;
for (Int64 x = 2; x <= Half; x++)
{
if (Num % x == 0)
return true;
}
return false;
}
#endregion