From d85c16efe083e08cddf06036b03fe1c570e6fcb1 Mon Sep 17 00:00:00 2001 From: Tekunov Daniil Date: Sat, 26 May 2018 15:07:19 +0300 Subject: [PATCH] Update Problem2.scala --- scala/Problem2.scala | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/scala/Problem2.scala b/scala/Problem2.scala index ab5f31e..3815b7f 100644 --- a/scala/Problem2.scala +++ b/scala/Problem2.scala @@ -2,19 +2,30 @@ import scala.annotation.tailrec object Main extends App { - /** - * Basic algorithm with O(n) speed - */ - def basicAlgo(until: Int = 4000000) = { - @tailrec - def fibonacciRecursion(listOfFibs: List[Int] = List(), first: Int = 1, second: Int = 1): List[Int] = { - if (second >= until) listOfFibs - else if (second % 2 == 0) fibonacciRecursion(listOfFibs :+ second, second, first + second) - else fibonacciRecursion(listOfFibs, second, first + second) + def time[R](block: => R): R = { + val t0 = System.nanoTime() + val result = block // call-by-name + val t1 = System.nanoTime() + println("Elapsed time: " + (t1 - t0)*0.000000001 + "s") + result + } + + time { + /** + * Basic algorithm with O(n) speed + */ + def basicAlgo(until: Int = 4000000) = { + @tailrec + def fibonacciRecursion(listOfFibs: List[Int] = List(), first: Int = 1, second: Int = 1): List[Int] = { + if (second >= until) listOfFibs + else if (second % 2 == 0) fibonacciRecursion(listOfFibs :+ second, second, first + second) + else fibonacciRecursion(listOfFibs, second, first + second) + } + fibonacciRecursion() } - fibonacciRecursion() + + println(basicAlgo().sum) } - println(basicAlgo().sum) }