Different Functions, Same Output

The two functions shown below compute the n th n^\text{th} Fibonacci number .

For large values of n n , one of the functions is significantly faster than the other. Which function is faster, fib1 or fib2 ?

1
2
3
4
5
6
7
8
9
def fib1(n):
    if n == 0:
        result = 0
    elif n == 1:
        result = 1
    else:
        result = fib1(n - 1) + fib1(n - 2)

    return result 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def fib2(n):
    if n == 0:
        result = 0
    elif n == 1:
        result = 1
    else:
        a = 0
        b = 1
        for i in xrange(0, n - 1):
            result = a + b
            a = b
            b = result

    return result

fib1 is faster Both are equally fast fib2 is faster

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

0 solutions

No explanations have been posted yet. Check back later!

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...