0

I'm reading through SICP. It's my first introduction to computer science.

The book presents the Fibonacci algorithm below:

(define (fib n)
  (cond 
    ((= n 0) 0)
    ((= n 1) 1)
    (else (+ (fib (- n 1)) 
             (fib (- n 2))))))

The book mentions that the space this algorithm takes up is (n) and the time it takes is n). I understand the space complexity since it is the max depth of a tree, but I can't seem to wrap my head around how the time complexity is derived.

Flux
  • 9,805
  • 5
  • 46
  • 92
user168651
  • 35
  • 3

1 Answers1

1

If you write down how much time it takes in each case (1 is constant),

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

you see that it is exactly the same as the Fibonacci numbers.
And as the text (almost) says, Fib(n) is (φn).

molbdnilo
  • 64,751
  • 3
  • 43
  • 82
  • where φ = (1 + sqrt(5)) / 2? But that is the approximate size of the fib(n), not the complexity of computing it. – President James K. Polk May 18 '20 at 14:35
  • @PresidentJamesK.Polk If you take f(10) and use the substitution model you'll end up with a line adding 1's together f(10) times. Thus the complexity of `fib(n)` is `O(fib(n))` – Sylwester May 19 '20 at 21:23