I've been studying for interviews lately, and came across the computing of Fibonacci sequence question. I stumbled on this solution on the Wikipedia Rosetta page. They claim that it computes it in O(log (n)) time. However, wouldn't it be O(m(n)* log n ) where m(n) is the time for the multiplication of two numbers of n digits. I understand that it's O(log n ) arithmetic operations, but I don't believe it's also O( log n) time. Am I correct in this assumption or totally confused? Can someone clarify this for me?
Here's the code:
public class fibonacci {
public static long fib(long n) {
if (n <= 0)
return 0;
long i = (int) (n - 1);
long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2;
while (i > 0) {
if (i % 2 != 0) {
tmp1 = d * b + c * a;
tmp2 = d * (b + a) + c * b;
a = tmp1;
b = tmp2;
}
tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2));
tmp2 = d * (2 * c + d);
c = tmp1;
d = tmp2;
i = i / 2;
}
return a + b;
}
}