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 four million.
(defun fib(n)
(fib-iter 1 0 n))
(defun fib-iter(a b count_)
(if (= count_ 0)
b
(fib-iter (+ a b) a (- count_ 1))))
(defun GenerateList(n)
(if (< (fib n) 4000000)
(cons (fib n) (GenerateList (+ n 1)))))
(defun FilterEuler2List(seq)
(if (null seq)
nil
(if (evenp (car seq))
(cons (car seq) (FilterEuler2List (cdr seq)))
(FilterEuler2List (cdr seq)))))
;(apply #'+ (FilterEuler2List (GenerateList 0))
Solution one
(defun list-fibs (limit)
(let ((fibs '(2 1)))
(do ((nextfib (+ (car fibs) (cadr fibs))
(+ (car fibs) (cadr fibs))))
((> nextfib limit))
(setq fibs (cons nextfib fibs)))
fibs))
(defun euler2 ()
(reduce #'+ (remove-if-not #'evenp (list-fibs 1000000))))
(let ((fibs '(2 1)))
(do ((nextfib (+ (car fibs) (cadr fibs))
(+ (car fibs) (cadr fibs))))
((> nextfib limit))
(setq fibs (cons nextfib fibs)))
fibs))
(defun euler2 ()
(reduce #'+ (remove-if-not #'evenp (list-fibs 1000000))))
Solution two
(loop
for x = 1 then y
and y = 2 then (+ x y)
and z = 0 then (1+ z)
do (when (>= y 1000000) (return total))
when (evenp y)
sum y into total
end
)
for x = 1 then y
and y = 2 then (+ x y)
and z = 0 then (1+ z)
do (when (>= y 1000000) (return total))
when (evenp y)
sum y into total
end
)
Solution Three
(defun problem-2 ()
(loop for x = 1 then y
and y = 2 then (+ x y)
while (< x 1000000)
when (evenp x)
sum x))
(loop for x = 1 then y
and y = 2 then (+ x y)
while (< x 1000000)
when (evenp x)
sum x))
Solution Four
(defun fib (x &optional (y 0) (z 1))
(if (< x z)
nil
(append (list z) (fib x z (+ y z)))))
(reduce #'+ (remove-if-not #'evenp (fib 1000000)))
(if (< x z)
nil
(append (list z) (fib x z (+ y z)))))
(reduce #'+ (remove-if-not #'evenp (fib 1000000)))
No comments:
Post a Comment