Archive for the ‘Computer Science’ Category

Sieve of Eratosthenes in Scala

Friday, June 19th, 2009

Lately, I have been interested in the Scala programming language.  It is actually quite nice, and seems to really work with me and not against me.  I really like the way the functional aspects are combined with imperative, as it makes it so much easier to think about things when my mind is not in a pure-functional mindset.

Here’s one little snippet that I’ve been working on to learn some Scala, another sieve of eratosthenes.  It will work if pasted into the scala interpreter, and then just call the primes function.

def primes_aux(currentList:List[Int], stopNumber:Int) : List[Int] = {
  if(currentList == Nil)
    Nil
  else {
    val H = currentList.head
    if (H <= stopNumber)
       H :: primes_aux(currentList.tail.remove(num => (num % H) == 0), stopNumber)
    else
      currentList
  }
}

def primes(maxNumber:Int) : List[Int] = {
  primes_aux((2 to maxNumber).toList, Math.sqrt(maxNumber))
}

I tried really hard to shrink the code from the erlang version, and I was successful. It is much more succint.  I will probably find some better functions that can help me get rid of or at least simplify the logic.  I have a feeling this can be done in a few short lines of code.

Sieve of Eratosthenes in Erlang

Thursday, April 9th, 2009

This is my first real attempt at a semi-useful program in Erlang.  It is the Sieve of Eratosthenes, which is a prime number generator.  The main function is primes() which accepts the number that you would like to count up to.  Luckly, Erlang is a Functional language, so I was able to do some fun things.

I had to modify the algorithm, as the original algorithm uses arrays, and arrays aren’t really used in Erlang.  I suppose this is probably due to the functional roots that Erlang has.  Scheme in practice tends to stay away from vectors and uses lists more.  I decided to use lists in Erlang, and was able to do some nice recursion, as is normal with Scheme.

-module(sieve).
-export([primes/1]).

%% Removes the multiples of a number from a list
remove_multiples(_, []) -> [];
remove_multiples(N, [H|T]) when (H rem N == 0) ->
        remove_multiples(N, T);
remove_multiples(N, [H|T]) ->
        [H|remove_multiples(N, T)].

%% Generate primes by creating a list of numbers from 0 to N.
%% Then recurse through the list, eliminating multiples off the tail at each recursion.
primes(N) ->
        primes(lists:seq(2,N), math:sqrt(N)).
primes([H|T], StopNumber) when H =
        [H|primes(remove_multiples(H, T), StopNumber)]; %% Does this blow your mind?
primes(L,_)-> L.

I’m not experienced with Erlang yet, so my apologies if I have bad Erlang style.