Problem 2 » 履歴 » バージョン 4
Noppi, 2023/12/28 01:31
| 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 | 4 | Noppi | (define (fib-numbers num) |
| 21 | 3 | Noppi | (let loop ([first 0] [second 1] [result '(1 0)]) |
| 22 | 1 | Noppi | (let ([next (+ first second)]) |
| 23 | 3 | Noppi | (if (< num next) |
| 24 | 4 | Noppi | result |
| 25 | 1 | Noppi | (loop second next (cons next result)))))) |
| 26 | |||
| 27 | 4 | Noppi | (define (even-fib-numbers num) |
| 28 | (filter even? (fib-numbers num))) |
||
| 29 | |||
| 30 | 3 | Noppi | (define answer-2 |
| 31 | 4 | Noppi | (apply + (even-fib-numbers 4000000))) |
| 32 | 1 | Noppi | |
| 33 | (printf "2: ~D~%" answer-2) |
||
| 34 | ``` |