Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing even fibonacci numbers in lisp

I've just started learning Lisp, and I'm working through some Project Euler problems. I'm stuck on the one where you sum the even Fibonacci numbers below a max number. The things I've tried follow. I've read this post but I'm still not sure why neither of my ways works!

CL-USER> (defun sum-even-fibs (max)
           (do ((curr 0 next)
                (next 1 (+ curr next))
                (sum  0 (if (evenp curr) (+ sum curr))))
               ((> max curr) sum)))
SUM-EVEN-FIBS
CL-USER> (sum-even-fibs 10)
0


CL-USER> (defun sum-even-fibs (max)
           (let ((sum 0))
             (do ((curr 0 next)
                  (next 1 (+ curr next)))
                 ((> max curr))
               (if (evenp curr) 
                   (setq sum (+ sum curr))))
             (format t "~d" sum)))
SUM-EVEN-FIBS
CL-USER> (sum-even-fibs 10)
0
NIL
like image 390
lightlike Avatar asked Jan 14 '23 12:01

lightlike


1 Answers

Slightly 'better' version of the answer of arbautjc:

(loop for a = 0 then b and b = 1 then (+ a b) 
      while (< a 4000000) 
      when (evenp a) sum a)
like image 166
Rainer Joswig Avatar answered Jan 31 '23 10:01

Rainer Joswig