How can I generate series of Pell numbers instead of a specific one in Lisp

前端 未结 3 1655
清酒与你
清酒与你 2021-01-21 15:27

How do I use cons or other way to print a list of Pell numbers till the Nth number?

(defun pellse (k)
   (if (or (zerop k) (= k 1))
       k
   (+ (* 2 (pellse (         


        
3条回答
  •  感情败类
    2021-01-21 15:44

    Here is how to do it in a way that won’t be exponential:

    (defun pells (n)
      (loop repeat n
        for current = 0 then next
        and next = 1 then (+ (* 2 next) current)
        collect current))
    

    The time complexity to calculate the nth element given the two previous elements is O(log(Pn)) where Pn is the nth Pell number; you need log(Pn) bits for the answer and log(Pn) operations for the addition. We don’t actually need to work out what Pn is: It is defined by a simple linear recurrence relation so the solution must be exponential so log(Pn) = O(n). Therefore the complexity of calculating the first n Pell numbers is O(n*n) = O(n2).

    One cannot[*] do better than O(n2) as one must write O(n2) bits to represent all these numbers.

    [*] Although I very much doubt this, it might, in theory, be possible to represent the list in some more compact way by somehow sharing data.

提交回复
热议问题