Home > scala > Scala: Project Euler: Problem 2

Scala: Project Euler: Problem 2

November 22nd, 2009

Problem 2:

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

object Problem2 {
    def main(args : Array[String]) : Unit = {
      val max = 4000000
      val sum = sumOfFibNumbers(max, isEven, 0, 1, 0)
      println(sum)
    }

    def isEven(x:Int) : Boolean = x % 2 == 0

    def sumOfFibNumbers(max:Int, p:(Int => Boolean), n1:Int, n2:Int, sum:Int): Int = {
      if(n1 < max) {
        if(p(n1)) sumOfFibNumbers(max, p,  n2, n1+n2, sum + n1)
        else sumOfFibNumbers(max, p, n2, n1+n2, sum)
      }
      else sum
    }
}

scala

  1. No comments yet.
  1. No trackbacks yet.