Generating Fibonacci numbers in Haskell?

前端 未结 11 1057
有刺的猬
有刺的猬 2020-11-29 18:35

In Haskell, how can I generate Fibonacci numbers based on the property that the nth Fibonacci number is equal to the (n-2)th Fibonacci number plus the (n-1)th Fibonacci numb

11条回答
  •  旧时难觅i
    2020-11-29 19:20

    To expand on dtb's answer:

    There is an important difference between the "simple" solution:

    fib 0 = 1
    fib 1 = 1
    fib n = fib (n-1) + fib (n-2)
    

    And the one you specified:

    fibs = 1 : 1 : zipWith (+) fibs (tail fibs)
    

    The simple solution takes O(1.618NN) time to compute the Nth element, while the one you specified takes O(N2). That's because the one you specified takes into account that computing fib n and fib (n-1) (which is required to compute it) share the dependency of fib (n-2), and that it can be computed once for both to save time. O(N2) is for N additions of numbers of O(N) digits.

提交回复
热议问题