Skip to content

Commit

Permalink
Update Problem2.scala
Browse files Browse the repository at this point in the history
  • Loading branch information
ditekunov authored May 26, 2018
1 parent a06c332 commit d85c16e
Showing 1 changed file with 22 additions and 11 deletions.
33 changes: 22 additions & 11 deletions scala/Problem2.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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)

}

0 comments on commit d85c16e

Please sign in to comment.