Note that there are some explanatory texts on larger screens.

plurals
  1. POSieve of Eratosthenes in Erlang
    text
    copied!<p>I'm in the process of learning Erlang. As an exercise I picked up the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="noreferrer">Sieve of Eratosthenes</a> algorithm of generating prime numbers. Here is my code:</p> <pre><code>-module(seed2). -export([get/1]). get(N) -&gt; WorkList = lists:duplicate(N, empty), get(2, N, WorkList, []). get(thats_the_end, _N, _WorkList, ResultList) -&gt; lists:reverse(ResultList); get(CurrentPrime, N, WorkList, ResultList) -&gt; ModWorkList = markAsPrime(CurrentPrime, N, WorkList), NextPrime = findNextPrime(CurrentPrime + 1, N, WorkList), get(NextPrime, N, ModWorkList, [CurrentPrime|ResultList]). markAsPrime(CurrentPrime, N, WorkList) when CurrentPrime =&lt; N -&gt; WorkListMod = replace(CurrentPrime, WorkList, prime), markAllMultiples(CurrentPrime, N, 2*CurrentPrime, WorkListMod). markAllMultiples(_ThePrime, N, TheCurentMark, WorkList) when TheCurentMark &gt; N -&gt; WorkList; markAllMultiples(ThePrime, N, TheCurrentMark, WorkList) -&gt; WorkListMod = replace(TheCurrentMark, WorkList, marked), markAllMultiples(ThePrime, N, TheCurrentMark + ThePrime, WorkListMod). findNextPrime(Iterator, N, _WorkList) when Iterator &gt; N -&gt; thats_the_end; findNextPrime(Iterator, N, WorkList) -&gt; I = lists:nth(Iterator, WorkList), if I =:= empty -&gt; Iterator; true -&gt; findNextPrime(Iterator + 1, N, WorkList) end. replace(N, L, New)-&gt; {L1, [_H|L2]} = lists:split(N - 1, L), lists:append(L1, [New|L2]). </code></pre> <p>This code actually works :) . The problem is that I have this feeling that it is not the best possible implementation. </p> <p>My question is what would be the "erlangish" way of implementing the "Sieve of Eratosthenes"</p> <p>EDIT: OK, Andreas solution is very good but it is slow. Any ideas how to improve that? </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload