Fibonacci sequence in Ruby (recursion)

后端 未结 24 1238
悲&欢浪女
悲&欢浪女 2020-12-01 02:54

I\'m trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.

Any ideas what the problem mi

24条回答
  •  离开以前
    2020-12-01 03:36

    Recursion's very slow, here's a faster way

    a = []; a[0] = 1; a[1] = 1
    i = 1
    while i < 1000000
        a[i+1] = (a[i] + a[i-1])%1000000007
        i += 1
    end
    
    puts a[n]    
    

    It's O(1), however you could use matrix exponentiation, here's one of mine's implementation, but it's in java => http://pastebin.com/DgbekCJM, but matrix exp.'s O(8logn) .Here's a much faster algorithm, called fast doubling. Here's a java implementation of fast doubling.

    class FD {
    
        static int mod = 1000000007;
    
        static long fastDoubling(int n) {
            if(n <= 2) return 1;
            int k = n/2;
            long a = fastDoubling(k+1);
            long b = fastDoubling(k);
            if(n%2 == 1) return (a*a + b*b)%mod;
            else return (b*(2*a - b))%mod;
    }
    

    Yet, using karatsuba multiplication, both matrix exp. and fast doubling becomes much faster, yet fast doubling beats matrix exp. by a constant factor, well i didn't want to be very thorough here. But i recently did a lot of research on fibonacci numbers and i want my research to be of use to anyone willing to learn, ;).

提交回复
热议问题