Thursday, March 12, 2015

Problem 2 in Scala

/**
  * Even Fibonacci numbers: https://projecteuler.net/problem=2
  *
  * Each new term in the Fibonacci sequence is generated by adding the
  * previous two terms. By starting with 1 and 2, the first 10 terms will be:
  * 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
  *
  * By considering the terms in the Fibonacci sequence whose values do not
  * exceed four million, find the sum of the even-valued terms.
  */

import scala.collection.mutable.ListBuffer

val n = 4000000
var newElement = 0
val fibList = ListBuffer(1,2)
while (newElement <= n) {
val a = fibList.length
newElement = fibList(a - 1) + fibList(a - 2)
if (newElement <= n) fibList.append(newElement)
}

val answer = fibList.filter(_ % 2 == 0).sum

No comments:

Post a Comment