12/09/2015

[Java] Good Fibonacci algorithm

Here is an efficient implementation of the Fibonacci algorithm by Michael Goodrich. I found it to be very fast and you should think about using it instead of the textbook implementation of the algorithm which is highly unoptimized and will start crashing pretty much immediately when you raise the number you want to compute by little.

 public static long[] fibGood(int n) {  
   if (n < = 1) {  
     long[] answer = {n,0};  
     return answer;  
   } else {  
     long[] tmp = fibGood(n-1);  
     long[] answer = {tmp[0] + tmp[1], tmp[0]};  
     return answer;  
   }  
 }  


You will have the answer for fibGood(n) in fibGood(n)[0]

No comments:

Post a Comment

With great power comes great responsibility.

Da grandi poteri derivano grandi responsabilità.