The lisp-way to solve Fibonnaci

前端 未结 14 1469
别那么骄傲
别那么骄傲 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:01

    To expand on Danio's answer, the article at http://fare.tunes.org/files/fun/fibonacci.lisp presents two ways of making the code run faster. Using straight recursion (tail call or no) is O(2^n) and very slow. The difficulty is that each value gets calculated over and over again. You have to do things differently. The two recommendations are:

    1. Use an iterative approach.
    (defun bubble-fib (n)
      (declare (optimize (speed 3) (safety 0) (debug 0)))
      (check-type n fixnum)
      (loop repeat n
      with p = 0 with q = 1
      do (psetq p q
            q (+ p q))
      finally (return p)))
    
    1. Use Memoization. This means remembering the values see before and recalling them rather than recalculating them. The article provides a CL package that will do this as well as some code to do it yourself.

提交回复
热议问题