Learning Erlang using projecteuler.net

Some time ago I found a website called Project Euler which is basically a list of math problems that should be solved using some programming language. I have wanted to learn Erlang for quite some time, but was never really motivated to do anything about it, until now.

I decided to have a go at it, and started to learn Erlang, and I must admit; its pretty damn nice!

One problem with the problems on the project euler page is that they don't really encourage me to do distributed computing, so I decided to play around a little with that.

The problem.

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle numbers:
1*: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28*: 1,2,4,7,14,28 We can see that 28 is the first triangle number to have over five divisors. What is the value of the first triangle number to have over five hundred divisors?

Not the hardest nut to crack once you get the hold of it. After a bit of optimization of the code, it looked like this:

-author("Jannich Brendle, jannich@bredsaal.dk, http://blog.bredsaal.dk").  

server() ->  

server(Number) ->  
  receive {getwork, Worker_PID} -> Worker_PID ! {work,Number,Number+100},  
  {result,T} -> io:format("The result is: \~w.\~n", [T]);  
  _ -> server(Number)  

worker(Server_PID) ->  
  Server_PID ! {getwork, self()},  
  receive {work,Start,End} -> solve(Start,End,Server_PID)  

start() ->  
  Server_PID = spawn(p12dist, server, []),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]),  
  spawn(p12dist, worker, [Server_PID]).

solve(N,End,_) when N =:= End -> no_solution;

solve(N,End,Server_PID) ->  
  case (divisor(T,round(math:sqrt(T))) > 500) of  
    true ->  
      Server_PID ! {result,T};  
    false ->  

divisors(N) ->  

divisor(_,0) -> 1;  
divisor(N,I) ->  
  case (N rem I) =:= 0 of  
  true ->  
  false ->  

Written by Jannich Brendle tor 18 december 2008 In Programming

tags: erlangmathproject euler

Related posts