Problem 2 » 履歴 » バージョン 3
Noppi, 2023/12/27 12:09
| 1 | 1 | Noppi | [ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] |
|---|---|---|---|
| 2 | # [[Problem 2]] |
||
| 3 | |||
| 4 | 3 | Noppi | ## Even Fibonacci Numbers |
| 5 | 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: |
||
| 6 | $$1, 2, 3, 5, 8, 13, 21, 34, 55, 89, \dots$$ |
||
| 7 | By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. |
||
| 8 | |||
| 9 | ## 偶数のフィボナッチ数 |
||
| 10 | フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである. |
||
| 11 | $$1, 2, 3, 5, 8, 13, 21, 34, 55, 89, \dots$$ |
||
| 12 | 数列の項の値が400万以下のとき, 値が偶数の項の総和を求めよ. |
||
| 13 | |||
| 14 | 2 | Noppi | ```scheme |
| 15 | #!r6rs |
||
| 16 | 1 | Noppi | #!chezscheme |
| 17 | |||
| 18 | (import (chezscheme)) |
||
| 19 | |||
| 20 | 3 | Noppi | (define (make-fib-list num) |
| 21 | (let loop ([first 0] [second 1] [result '(1 0)]) |
||
| 22 | 1 | Noppi | (let ([next (+ first second)]) |
| 23 | 3 | Noppi | (if (< num next) |
| 24 | (reverse result) |
||
| 25 | (loop second next (cons next result)))))) |
||
| 26 | |||
| 27 | (define answer-2 |
||
| 28 | (fold-left |
||
| 29 | (lambda (sum current) |
||
| 30 | (if (even? current) |
||
| 31 | (+ sum current) |
||
| 32 | sum)) |
||
| 33 | 0 |
||
| 34 | (make-fib-list 4000000))) |
||
| 35 | 1 | Noppi | |
| 36 | (printf "2: ~D~%" answer-2) |
||
| 37 | ``` |