Skip to content

Instantly share code, notes, and snippets.

@dimdim2
Last active December 16, 2015 08:19
Show Gist options
  • Save dimdim2/5405217 to your computer and use it in GitHub Desktop.
Save dimdim2/5405217 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object Problem2 {
def fib(n: Int): Int = {
@tailrec
def run(n: Int, i: Int = 1, acc1: Int = 1, acc2: Int = 1): Int = {
if(n <= i) acc1
else run(n, i+1, acc2, acc1 + acc2)
}
if (n < 2) n else run(n)
}
@tailrec
def fibSum(max: Int, sum: Int = 0, num: Int = 2): Int = {
fib(num) match {
case n if n > max => sum
case n if n % 2 == 0 => fibSum(max, sum + n, num+1)
case _ => fibSum(max, sum, num+1)
}
} //> fibSum: (max: Int)Int
fibSum(4000000) //> res0: Int = 4613732
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment