Search Results

Search found 1 results on 1 pages for 'firephil'.

Page 1/1 | 1 

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

    - by firephil
    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 ?

    Read the article

1