ScalaでProject Euler(43)

Problem 25

多倍長整数ですが、加算だけなので簡単ですね。

import Stream.cons

def add(a :List[Int], b :List[Int], c :Int) :List[Int] = (a, b, c) match {
    case (h1 :: t1, h2 :: t2, c) => {
        val s = h1 + h2 + c
        s % 10 :: add(t1, t2, s / 10)
    }
    case (h1 :: t1, Nil, c) => (h1 + c) % 10 :: add(t1, Nil, (h1 + c) / 10)
    case (Nil, h2 :: t2, c) => (h2 + c) % 10 :: add(Nil, t2, (h2 + c) / 10)
    case (Nil, Nil, 0) => Nil
    case (Nil, Nil, c) => List(c)
}

val N = 1000
val fib :Stream[List[Int]] = cons(List(1), cons(List(1),
                    fib.zip(fib.tail).map(x => add(x._1, x._2, 0))))
println (fib.zip(Stream.from(1)).dropWhile(x => x._1.size < N).map(_._2).head)