-
Notifications
You must be signed in to change notification settings - Fork 0
/
p1.scm
65 lines (57 loc) · 1.82 KB
/
p1.scm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
;; 24 December 2007
;;
;; Yuri Arapov <[email protected]>
;;
;; Project Euler
;;
;; http://projecteuler.net/index.php?section=problems&id=2
;;
;; Problem 2
;; 19 October 2001
;;
;; 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, ...
;;
;; Find the sum of all the even-valued terms in the sequence
;; which do not exceed one million.
;;
;; Answer:
;; 1089154
;; 1089154 (scheme)
;;
;; Done.
;;
;; Some useful references:
;; http://en.wikipedia.org/wiki/Fibonacci_sequence
;; http://en.wikibooks.org/wiki/Fibonacci_number_program
;; http://mathworld.wolfram.com/FibonacciNumber.html
(define (fib n)
(define (iter a b nn)
(if (= nn 0)
b
(iter b (+ b a) (- nn 1))))
(iter 1 0 n))
(define (p1)
(define (iter n s)
(define x (fib n))
(if (<= x 1000000) ;; x does not exeed one million
(if (= 0 (remainder x 2)) ;; x is even
(iter (+ n 1) (+ s x)) ;; add x to the result and try next fibonacci number
(iter (+ n 1) s)) ;; try next fibonacci number
s)) ;; return result
(iter 0 0))
(define (p1-v2 upper-limit)
(define (even? x) (= 0 (remainder x 2)))
(define (iter fn-1 fn s)
;; fn-1 stands for f(n-1)
;; fn stands for f(n)
(if (> fn upper-limit) ;; stop the loop and
s ;; return the result
(iter fn (+ fn-1 fn) (if (even? fn) (+ s fn) s)))) ;; add current fibonacci number
;; to resultant sum (if it's even)
;; and go to next fibonacci number
(iter 0 1 0)) ;; start from f(1)==1
;; end of file