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

前端 未结 8 1856
难免孤独
难免孤独 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 11:39

    If you have access to the Symbolic Math Toolbox in MATLAB, you could always just call the Fibonacci function from MuPAD:

    >> fib = @(n) evalin(symengine, ['numlib::fibonacci(' num2str(n) ')'])
    >> fib(274)
    ans =
    818706854228831001753880637535093596811413714795418360007
    

    It is pretty fast:

    >> timeit(@() fib(274))
    ans =
        0.0011
    

    Plus you can you go for as large numbers as you want (limited only by how much RAM you have!), it is still blazing fast:

    % see if you can beat that!
    >> tic
    >> x = fib(100000);
    >> toc               % Elapsed time is 0.004621 seconds.
    
    % result has more than 20 thousand digits!
    >> length(char(x))   % 20899
    

    Here is the full value of fib(100000): http://pastebin.com/f6KPGKBg

提交回复
热议问题