language: Scala (scala-2.10.0)
date: 843 days 23 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
object Main {
  def main(args: Array[String]) {
                println("Euler Question #1: Add all the natural numbers below one thousand that are multiples of 3 or 5.")
                var start = System.currentTimeMillis()
                val answer1 = (1 until 1000).foldLeft(0){(total, x) => 
                  x match {
                    case i if (i % 3 == 0 || i % 5 ==0) => i + total
                    case _ => total
                  }
                }
                var end = System.currentTimeMillis()
                println("Answer: " + answer1)
                println("Time: " + (end - start) + "ms")
 
                println("Trying it another way, using a pattern match instead of filter...")
                start = System.currentTimeMillis()
                val answer2 = (1 until 1000).filter(i => (i % 3 == 0 || i % 5 == 0)).foldLeft(0)(_ + _)
                end = System.currentTimeMillis()
                println("The other way gets the right answer: " + answer2)
                println("but get the answer much faster: " + (end - start) + "ms")
  }
}