On Thursday, 5 April 2012 at 17:22:38 UTC, Minas wrote:
Many of you should know the website "projecteuler.net", where
there are mathematical problems to solve with computers.
I am doing those in D, and after I finished one today, I
decided to compile it in C as well to compare the results.
The problem was:
"The number 3797 has an interesting property. Being prime
itself, it is possible to continuously remove digits from left
to right, and remain prime at each stage: 3797, 797, 97, and 7.
Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both
truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable
primes."
My solution in D:
First, you should compile with -O -release -inline and, in this
case, -noboundscheck.
The main issue here seems to be the for loop.
Changing:
for(ulong i = 2; i <= cast (ulong)sqrt(cast(double)n+1); ++i)
if( n % i == 0 )
return false;
To:
ulong End = cast (ulong)sqrt(cast(double)n+1);
for(ulong i = 2; i <= End; ++i)
if( n % i == 0 )
return false;
Results in a 26 times performance increase for me, based off of
using a StopWatch at start of main and stopping it at end of
main. It's possible that the C compiler can recognize that this
is a constant expression (sqrt might be an intrinsic). D should
be able to do this even better; sqrt is strongly pure and takes
in arguments that do not change, thus it should be able to
automatically make the change I did above. It (at least DMD) does
not seem to however.
I did not try the C version, and the D version was compiled with
DMD on Windows.