The Problem:
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.
This was my first solution [Sol1]:
def getTotal(upper:Int) : Int = multiplesBelow(upper - 1)
def multiplesBelow(start:Int) : Int = {
if (start <= 0) return 0
if (isMultiple(start)) start + multiplesBelow(start-1) else multiplesBelow(start - 1)
}
def isMultiple(number:Int) : Boolean = (number != 0) && ((number % 3 == 0) || (number % 5 == 0))
Although this solution will give you the expected answer with the following:
getTotal(1000)
Sol1 is quite clumsy. After a quite scout around the net I found a ruby solution that used ranges and since scala also has ranges I came up with the following [Sol2]:
def getTotal2(upper:Int) : Int = (1 until upper).foldLeft(0)(((a,b) => if (b % 3 == 0 || b % 5 == 0) a+b else a))
I like Sol2 mainly because it is succinct and "simple". I also came up with a solution using map and fold [Sol3]:
def getTotal3(upper:Int) : Int = (1 until upper).map(a => if (a % 3 == 0 || a % 5 == 0) a else 0).foldLeft(0)(_ + _)
Sol3 has an extra step of mapping the function across the values and then folding it.
And there you have the solution to problem 1. I'm sure there are much neater solutions to problem than those above. Please feel free to comment if you have a better solution and/or comments.
0 comments:
Post a Comment