At our company we have a Xojo fan, a C# fan and a Python fan.
We decided to have a little bit of fun and play a game to see which language runs a certain algorithm the fastest.
Here are the rules of the game:
Calculate the sum of all the prime numbers between 0 and 1,000,000. As output give the sum, total number of prime numbers, and the running time.
Currently I get Xojo to complete the taksk in 1.26s (compiled, not via IDE). C# is currently the winner completing the task in 0.4s (YES, a fraction of a second).
Something I already learned, it is better to use UInt32 instead of UInt64 where possible. With UInt64 my algorithm ran 2.4s, with UInt32 at ran 1.26s.
Here is the algorithm I used:
Dim i As UInt32
Dim j As UInt32
Dim total As UInt64
Dim count As UInt32
Dim max As UInt32
Dim isPrime As Boolean
Dim startTime As Double
Dim endTime As Double
startTime = Microseconds()
total = 2
count = 0
i = 3
while i <= 1000000
max = Sqrt(i)
isPrime = true
j = 2
while (j <= max) and isPrime
if (i mod j) = 0 then
isPrime = false
end if
j = j + 1
wend
if isPrime then
total = total + i
count = count + 1
end if
i = i + 2
wend
endTime = Microseconds()
System.DebugLog "Items: " + Str(count) + EndOfLine + _
"Sum: " + Str(total) + EndOfLine + _
"Time: " + Str((endTime - startTime) / 1000000, "##########0.000000") + " seconds"
Can anyone spot obvious improvements I can make? Would be great if I could get it to run faster than C#.
FWIW, here is the C# code that currently beats my code:
using System;
using System.Diagnostics;
namespace PrimeNumberPuzzel
{
class Program
{
static void Main(string[] args)
{
int i = 3, j, count = 0;
double max, total = 2;
bool isPrime;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while (i <= 1000000)
{
max = Math.Sqrt(i);
isPrime = true;
j = 2;
while (j <= max && isPrime)
{
if (i % j == 0)
isPrime = false;
j += 1;
}
if (isPrime)
{
total += i;
count ++;
}
i += 2;
}
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Console.WriteLine(String.Format("Items: {0}", count));
Console.WriteLine(String.Format("Sum: {0}", total));
Console.WriteLine(String.Format("Time: {0}", ts));
Console.ReadLine();
}
}
}
PS. If anyone knows why in the world C# would run so much faster, it would be nice if you could share your wisdom.