Create faster Fibonacci function for n > 100 in MATLAB / octave

前端 未结 8 1821
难免孤独
难免孤独 2020-12-31 11:34

I have a function that tells me the nth number in a Fibonacci sequence. The problem is it becomes very slow when trying to find larger numbers in the Fibonacci sequence doe

相关标签:
8条回答
  • 2020-12-31 12:05

    One performance issue is that you use a recursive solution. Going for an iterative method will spare you of the argument passing for each function call. As Olivier pointed out, it will reduce the complexity to linear.

    You can also look here. Apparently there's a formula that computes the n'th member of the Fibonacci sequence. I tested it for up to 50'th element. For higher n values it's not very accurate.

    0 讨论(0)
  • 2020-12-31 12:05

    One simple way to speed up the recursive implementation of a Fibonacci function is to realize that, substituting f(n-1) by its definition,

    f(n) = f(n-1) + f(n-2)
         = f(n-2) + f(n-3) + f(n-2)
         = 2*f(n-2) + f(n-3)
    

    This simple transformation greatly reduces the number of steps taken to compute a number in the series.

    If we start with OP's code, slightly corrected:

    function result = fibonacci(n)
    switch n
    case 0
       result = 0;
    case 1
       result = 1;
    case 2
       result = 1;
    case 3
       result = 2;
    otherwise
       result = fibonacci(n-2) + fibonacci(n-1);
    end
    

    And apply our transformation:

    function result = fibonacci_fast(n)
    switch n
    case 0
       result = 0;
    case 1
       result = 1;
    case 2
       result = 1;
    case 3
       result = 2;
    otherwise
       result = fibonacci_fast(n-3) + 2*fibonacci_fast(n-2);
    end
    

    Then we see a 30x speed improvement for computing the 20th number in the series (using Octave):

    >> tic; for ii=1:100, fibonacci(20); end; toc
    Elapsed time is 12.4393 seconds.
    >> tic; for ii=1:100, fibonacci_fast(20); end; toc
    Elapsed time is 0.448623 seconds.
    

    Of course Rashid's non-recursive implementation is another 60x faster still: 0.00706792 seconds.

    0 讨论(0)
提交回复
热议问题