December 8, 2011 Leave a comment
I was helping my son with math homework today.. One of the problems was to find all prime numbers up to a 100.. That was enough for me to start looking for an old Erlang script I have played with few years ago…
-module(eratosthenes). -export([prime_numbers/1]). % Sieve of Eratosthenes algorithm for finding all prime numbers up to N. % http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes % Generate list of prime numbers up to N. prime_numbers(N) when is_number(N) -> prime_numbers(N, generate(N)). prime_numbers(Max, [H|T]) when H * H =< Max -> [H | prime_numbers(Max, [R || R <- T, (R rem H) > 0])]; prime_numbers(_, T) -> T. % Generate sequence 2..N generate(N) -> generate(N, 2). generate(Max, Max) -> [Max]; generate(Max, X) -> [X | generate(Max, X + 1)].
What can I say… Love Erlang🙂