Last active
December 16, 2015 11:09
-
-
Save outsideris/5425790 to your computer and use it in GitHub Desktop.
euler for PiS Study
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package kr.ne.outsider | |
object p002 extends App { | |
var cache:Map[Int, Int] = Map() | |
def fibonacci(x: Int): Int = { | |
cache.get(x) match { | |
case Some(t) => t | |
case _ => { | |
x match { | |
case 0 => cache += (x -> x); x | |
case 1 => cache += (x -> x); x | |
case _ => { | |
val temp = fibonacci(x-1) + fibonacci(x-2) | |
cache += (x -> temp) | |
temp | |
} | |
} | |
} | |
} | |
} | |
def _loop(x: Int, accum: Int): Int = { | |
val temp = fibonacci(x) | |
temp match { | |
case a if a >= 4000000 => accum | |
case a if a % 2 == 0 => _loop(x + 1, accum + temp) | |
case _ => _loop(x + 1, accum) | |
} | |
} | |
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) + "ns") | |
result | |
} | |
println(time {_loop(1, 0)}) // Elapsed time: 6742000ns | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment