<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
</head>
<body bgcolor="#FFFFFF" text="#000000">
Hi everyone,<br>
<br>
I am new to Erlang and exercise by solving project-euler problems.
The current one is this<br>
<p><b>The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.</b><b>
Find the sum of all the primes below two million.</b><br>
</p>
<p>I tried two approaches which work for small numbers but take way
too long for larger inputs like 2 million. Is there anything to
improve performance or is Erlang simply not made for problems like
this?<br>
I would be happy to get some feedback on my code. For example I am
not sure if it is a developer's task to keep track of variables
like Max in the second example. (I've only included this because
it is not allowed to use functions inside guard expressions).<br>
</p>
<br>
%1st approach:<br>
%returns a lists of prime numbers smaller than N<br>
%this works by eliminating non-prime numbers from the sequence(1,N)
in N steps<br>
<br>
<blockquote>-module(primes).<br>
-export([primelist/1]).<br>
<br>
primelist(N) -> primelist(lists:seq(1,N),N,2).<br>
<br>
primelist(Filterlist,Max,I) when I<Max<br>
-> primelist([X||X<-Filterlist,(X==I) or (X rem I /=
0)],Max,I+1);<br>
primelist([],Max,I)<br>
-> [];<br>
primelist(Filterlist,Max,I) when I == Max<br>
-> Filterlist.<br>
</blockquote>
<br>
%2nd approach<br>
%returns the sum of the primes up to N<br>
%the function successively builds up a list of primes by testing
candidates<br>
%and sums it afterwards<br>
<br>
<blockquote>-module(prime9).<br>
-export([sumprimes/1]).<br>
<br>
sumprimes(N) -> sumprimes(N,[2],[2],2,3).<br>
<br>
sumprimes(N,[H|T],L,Max,Try) when (Max<N) andalso (Try rem H /=
0)<br>
-> sumprimes(N, T,L, Max, Try);<br>
sumprimes(N,[H|T],L,Max,Try) when (Max<N) andalso (Try rem H ==
0)<br>
-> sumprimes(N, L,L, Max, Try+1);<br>
sumprimes(N,[2],L,Max,Try) when (Try rem 2 /= 0)<br>
-> sumprimes(N,[],L,Max,Try);<br>
sumprimes(N,[2],L,Max,Try) when (Try rem 2 == 0)<br>
-> sumprimes(N,L,L,Max,Try+1);<br>
sumprimes(N,[],L,Max,Try) when (Max<N)<br>
->
sumprimes(N,lists:append([Try],L),lists:append([Try],L),Try,Try+1);<br>
sumprimes(N,L,[H|T],Max,Try) when (Max >= N)<br>
-> lists:sum(T).<br>
<br>
<br>
</blockquote>
Thank you very much& best regards<br>
Damian<br>
</body>
</html>