Thursday, May 12, 2011

02 Kata [scala] - sum of even fibonacci numbers

Here is the first tentative using brute force.

class SecondKata {
  var sum:Long = 0;

  def sum(limit: Long): Long = {
    var sum: Long = 0

    (for (i: Long <- 0l to 40l; j = fib(i); if (j < limit) && isEven(j)) yield j).foreach(sum += _)

    sum
  }

  def isEven(n: Long): Boolean = {
    return (n % 2) == 0
  }

  def fib(n: Long): Long = {
    if ((n < 2)) n else fib(n - 1) + fib(n - 2)
  }
}
And here is the second tentative using a little big of math magic.
class SecondKata {
  def sum(limit: Long): Long = {
    val n: Long = round(((log(limit * sqrt(5))) * 2) + 1.618)

    var sum: Long = 0

    (for (i: Long <- 6l to 40l;
          j = (4 * fib(i - 3)) + fib(i - 6);
          if (j < limit) && isEven(j)
    ) yield j).foreach(sum += _)

    sum + 2
  }

  def isEven(n: Long): Boolean = {
    return (n % 2) == 0
  }

  def fib(n: Long): Long = {
    if ((n < 2)) n else fib(n - 1) + fib(n - 2)
  }
}

No comments:

Post a Comment