Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 does anyone know how I can fix this?

function f = rtfib(n)
 if (n==1)
     f= 1;
 elseif (n == 2)
     f = 2;
 else
     f =rtfib(n-1) + rtfib(n-2);   
 end

The Results,

tic; rtfib(20), toc
ans =  10946
Elapsed time is 0.134947 seconds.

tic; rtfib(30), toc
ans =  1346269
Elapsed time is 16.6724 seconds.

I can't even get a value after 5 mins doing rtfib(100)

PS: I'm using octave 3.8.1

like image 534
Rick T Avatar asked Nov 09 '14 14:11

Rick T


People also ask

What is the Fibonacci series of 100?

The list of first 20 terms in the Fibonacci Sequence is: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181.

What is f14 in Fibonacci?

F(14)=377. F(15)=610. F(16)=987. F(17)=1597. F(18)=2584.

How do you express the Fibonacci sequence?

The Fibonacci formula is given as, Fn = Fn-1 + Fn-2, where n > 1.


Video Answer


1 Answers

You can do it in O(log n) time with matrix exponentiation:

X = [0 1
     1 1]

X^n will give you the nth fibonacci number in the lower right-hand corner; X^n can be represented as the product of several matrices X^(2^i), so for example X^11 would be X^1 * X^2 * X^8, i <= log_2(n). And X^8 = (X^4)^2, etc, so at most 2*log(n) matrix multiplications.

like image 182
Max Avatar answered Sep 23 '22 11:09

Max