Project Euler is a bunch of mathematical/programming problems. I’ve been trying to improve my Scala skills by using it on some of the Euler problems. I’m trying to use functional programming styles as much as possible. My solutions definitely haven’t been very optimized, but I am learning, which is the aim.
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
My solution:
def sum(nums: Iterable[Int]): Int = (0 /: nums)(_ + _) println(sum((3 until 1000).filter(i => i%3 == 0 || i%5 == 0)))
The 3 until 1000
creates a “range”, which is a lazy sequence of numbers from 3 to 999 inclusive. Because it’s lazy, you don’t get 997 integers sitting around in memory, you only get those integers which pass the filter. The filter itself shows the Scala syntax for a “lambda expression” (anonymous function). The full syntax is (arg1, arg2, ..) => function body
, but when you only have one argument (a single Int, in this case) you can leave out the brackets.
The sum
function is the operator syntax for a left fold over nums
. The _+_
is an even more terse form of a lambda expression that you can use for really simple expressions. The first underscore is replaced by the first argument to the function, and the second is replaced by the second argument.
Comments !