Tag Archives: Euler

Euler problems in Scala

SRT is abuzz with solving the Euler problems, in our collective spare time, and in different languages.

Bill Wagner has been solving the problems on euler.net in C#/LINQ.  Darrell Hawley is attacking them in Python.  Marina Fedner is giving us a flavor for Ruby.  And so I'll jump in, in Scala.   And no, we're not looking at each other's solutions before doing our own! 

Here's my Scala solution to problem 1, which is to sum the numbers between 0 and 1000 that are divisible by either 3 or 5.

    val nums = 3 until 1000
   
    val somenums = nums.filter(x => (x % 3 == 0 || x % 5 ==0))
   
    var sum = 0

    somenums.foreach(sum += _)
    println (sum)

I figured that there was no sense starting with a number less than 3 (not that it made much difference to the solution, but what the heck).  The filter function (on lists) in Scala provides a nice way to grab the appropriate values.  The foreach expression, when combined with the "_", which is a placeholder for the parameter. 

 Alternately, I could have defined a temporary variable x, like this:

for (x <- somenums)   sum += x
 

So, does the temporary variable "x" improve readability?  Perhaps somewhat, until you get used to the new syntax.  There are certainly times in Scala where I appreciate the more verbose syntax (and am grateful for its legality), but in this case, I prefer the more concise "foreach".

Sidenote: as Bill mentioned in his solution, the goal here is not necessarily to provide the most optimal, functional solution.  It's to provide one that works, and learn/expose information about how to use the language along the way.  And people who are interested in solving the problems themselves should probably avoid our posts on this subject.