Factor in Erlang

 The first piece of code that I wrote in Erlang was to factor numbers.  I thought it would be a good test to learn the basics of Erlang (very basics).  I have appended the code to this post.  I am not sure if it the fastest way to factor a number (vs building up the list, but it would have to pass an accumulator around), I will have to investigate that in the future, but it served its purpose for now. 

I then used this code to test which machines and implementations of Erlang were the fastest and got some interesting results.  The code factored 380312393432894324523423103, which I discovered by typing in random numbers to factor.  It has a large factor, 9517107199440611, which makes it a reasonable benchmark for a simple test.  Here are my results:

AMD 64, 4600+, Windows XP -> 15.4 seconds
MacPro, 2.66 Xeon, Linux -> 3.7 seconds
MacPro, 2.66 Xeon, MacOSX -> 7.0 seconds
MacPro, 2.66 Xeon, Vista64 -> 7.3 seconds

I only have one OS on the AMD, but it would be interesting to see if Linux is 2x faster, as it was on the MacPro.  I was surprised that the Xeon chipset in the MacPro was so much faster than the AMD64, but I guess they are more than a year apart in age.

-Edward

fac(N) -> fac(N,2).
fac(N, F) when F*F > N -> [N];
fac(N, F) when N rem F =:= 0 -> [F | fac(N div F, F)];
fac(N, 2) -> fac( N, 3 );
fac(N, F) -> fac(N, F+2).

Leave a Reply

You must be logged in to post a comment.