Better way for calculating project euler's 2nd problem Fibonacci sequence)

Posted by firephil on Programmers See other posts from Programmers or by firephil
Published on 2013-10-28T19:41:23Z Indexed on 2013/10/28 22:10 UTC
Read the original article Hit count: 183

Filed under:
|
object Problem_2 extends App {
def fibLoop():Long =
  {
  var x = 1L
  var y = 2L
  var sum = 0L
  var swap = 0L

  while(x < 4000000)
  {
    if(x % 2 ==0) sum +=x
    swap = x
    x = y
    y = swap + x
  }
  sum
 }
 def fib:Int = {
 lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p => p._1 + p._2)
 fs.view.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum
}


  val t1 = System.nanoTime()
  val res = fibLoop
  val t2 = (System.nanoTime() - t1 )/1000 
  println(s"The result is: $res time taken $t2 ms ")

 }

Is there a better functional way for calculating the fibonaci sequence and taking the sum of the the even values below 4million ? (projecteuler.net -> problem 2)

The imperative method is 1000x faster ?

© Programmers or respective owner

Related posts about scala

Related posts about efficiency