The lisp-way to solve Fibonnaci

前端 未结 14 1688
别那么骄傲
别那么骄傲 2021-02-08 07:17

I wanted to try and learn Lisp, but I very quickly gave up. I figured I\'d try again. I\'m looking at Problem 2 on Project Euler - finding the sum of all even Fibonacci numbers

14条回答
  •  半阙折子戏
    2021-02-08 08:13

    Simple, efficient way of creating a list of fibonacci numbers:

    (defun fibs (n &optional (a 1) (b 1))
      (loop repeat n 
            collect (shiftf a b (+ a b))))

    (shiftf) takes any number of places and finally a value. Each place is set to the value of the next variable, with the last variable taking the value that comes after it. It returns the value of the first place. In other words, it shifts all the values left by one.

    However, you don't need the full list (you only need the evens) and you don't need the list at all (you only need the sum), so this can be worked into the function directly. Every third fibonacci number is even, so...

    (defun euler-2 (limit &optional (a 1) (b 1))
      (loop for x upfrom 1
            until (> a limit)
            if (zerop (mod x 3)) 
               sum a
            do (shiftf a b (+ a b))))

提交回复
热议问题