Search code examples
algorithmrecurrence

Running Time of Divide And conquer fibonacci program


count = 0
def fibonacci(n):
    global count
    count = count + 1
    if not isinstance(n, int):
        print ('Invalid Input')
        return None

    if n < 0:
        print ('Invalid Input')
        return None

    if n == 0:
        return 0

    if n == 1:
        return 1

    fib = fibonacci(n-1) + fibonacci(n-2)
    return fib

fibonacci(8)
print(count)

I was trying to find out the running time of this fibonacci program. Can any one help me in solving the recurrence relation for the same..

T(n) = T(n-1) + T(n-2)...What would be the running time calculation from here?

Thanks... :)


Solution

  • you can see wiki, But simple observation As you wrote:

     T(n) < 2T(n-1) = 2 * 2 T(n-2) =.... = 2^(n-1)T(1) = 2^(n-1). So T(n) is in O(2^n).
    

    in fact you should solve x^2 = X + 1 so x will be phi1 = (1+sqrt(5))/2 or phi2 = (1-sqrt(5))/2 so result is phi1 ^ n + phi2 ^n but because phi2 is smaller than 1 for big n we can say it's T(n)=phi1^n.

    Edit:*But you can edit your current solution to take O(n) running time(by for loop start from first element).