ONLY DO WHAT ONLY YOU CAN DO

こけたら立ちなはれ 立ったら歩きなはれ

Scala で Project Euler Problem 2

フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである.

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

数列の項の値が400万を超えない範囲で, 偶数値の項の総和を求めよ.

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

まず、フィボナッチ数列の List を作成し、

1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040
1346269
2178309
3524578

Filetr によって偶数のみ抽出し

2
8
34
144
610
2584
10946
46368
196418
832040
3524578

sum で結果を得る。

scala> List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578)
res0: List[Int] = List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578)

scala> List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578).filter(n => n % 2 == 0)
res1: List[Int] = List(2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578)

scala> List(1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578).filter(n => n % 2 == 0).sum
res2: Int = 4613732

scala>
scala> def fib (fib_list:List[Int]) = {
     |     val i:Int = fib_list(0) + fib_list(1)
     |     if (i <= 4000000) fib(i::fib_list)
     |     else              fib_list
     | }
<console>:12: error: recursive method fib needs result type
           if (i <= 4000000) fib(i::fib_list)
                             ^

scala> def fib (fib_list:List[Int]):List[Int] = {
     |     val i:Int = fib_list(0) + fib_list(1)
     |     if (i <= 4000000) fib(i::fib_list)
     |     else              fib_list
     | }
fib: (fib_list: List[Int])List[Int]

scala> val fib_list = List(2, 1)
fib_list: List[Int] = List(2, 1)

scala> fib(fib_list)
res0: List[Int] = List(3524578, 2178309, 1346269, 832040, 514229, 317811, 196418, 121393, 75025, 46368, 28657, 17711, 10946, 6765, 4181, 2584, 1597, 987, 610, 377, 233, 144, 89, 55, 34, 21, 13, 8, 5, 3, 2, 1)

scala> fib(fib_list).filter(_ % 2 == 0)
res1: List[Int] = List(3524578, 832040, 196418, 46368, 10946, 2584, 610, 144, 34, 8, 2)

scala> fib(fib_list).filter(_ % 2 == 0).sum
res2: Int = 4613732

scala>