Problem 1


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.

Brute Force


In scala, adding to a variable isn't good form, the proper way to brute force through every value in a range is to use recursion. And to keep from blowing the stack, I make sure it's tail recursive.


In [13]:
@annotation.tailrec
final def natural3and5brute(upper:Int = 1000, current:Int = 1, output:Int = 0):Int = {
  if (current == upper) output
  else {
      val newout:Int = if (current % 3 == 0 | current % 5 == 0) output + current else output
      natural3and5brute(upper, current + 1, newout)
  }
}


defined function natural3and5brute

In [14]:
natural3and5brute()


res9: Int = 233168

In [ ]: