プロジェクト

全般

プロフィール

Problem 2 » 履歴 » リビジョン 3

リビジョン 2 (Noppi, 2023/12/27 04:43) → リビジョン 3/4 (Noppi, 2023/12/27 12:09)

[ホーム](https://redmine.noppi.jp) - [[Wiki|Project Euler]] 
 # [[Problem 2]] 

 ## Even Fibonacci Numbers 
 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, \dots$$ 
 By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. 

 ## 偶数のフィボナッチ数 
 フィボナッチ数列の項は前の2つの項の和である. 最初の2項を 1, 2 とすれば, 最初の10項は以下の通りである. 
 $$1, 2, 3, 5, 8, 13, 21, 34, 55, 89, \dots$$ 
 数列の項の値が400万以下のとき, 値が偶数の項の総和を求めよ. 

 ```scheme 
 #!r6rs 
 #!chezscheme 

 (import (chezscheme)) 

 (define (make-fib-list num) answer-2 
   (let loop ([first 0] [second 1] [result '(1 0)]) 0]) 
     (let ([next (+ first second)]) 
       (if (< num (cond 
         [(< 4000000 next) result] 
         (reverse result) 
         [(even? next) 
          (loop second next (cons next result)))))) 

 (define answer-2 
   (fold-left 
     (lambda (sum current) 
       (if (even? current) 
         (+ sum current) result next))] 
         sum)) 
     0 
     (make-fib-list 4000000))) [else (loop second next result)])))) 

 (printf "2: ~D~%" answer-2) 
 ```