Optimization of Fibonacci sequence generating algorithm
As we all know, the simplest algorithm to generate Fibonacci sequence is as follows: if(n<=0) return 0; else if(n==1) return 1; f(n) = f(n-1) + f(n-2); But this algorithm has some repetitive calculation. For example, if you calculate f(5), it will calculate f(4) and f(3). When you calculate f(4), it will again calculate both f(3) and f(2). Could someone give me a more time-efficient recursive algorithm? One simple way is to calculate it iteratively instead of recursively. This will calculate F(n) in linear time. def fib(n): a,b = 0,1 for i in range(n): a,b = a+b,a return a Hynek -Pichi-