Alvaro wrote:It uses a faster algorithm. Can anybody figure out how it works?
I got this far:
- Code: Select all
for(int i=2;i<20;++i)
std::cout << i << ' '
<< fib(i) << std::endl;
fib(i) will call the function with the value of 2
- Code: Select all
return power(FibMatrix(0,1),n).b;
The first thing here is to call FibMatrix constructor with 0 and 1, when that returns then the power function is called and passed a object of FibMatrix and the value of n which is 2.
Now in the power function we have:
- Code: Select all
return n?(n&1?x*power(x,n-1):power(x*x,n>>1)):T(1);
since n is two that is true so we go to :
- Code: Select all
power(x*x,n>>1)
Here we call the operator * for x*x :
- Code: Select all
return FibMatrix(a*s.a+b*s.b,a*s.b+b*(s.a+s.b));
in here it breaks down like this:
I will replace the letters with their values
(0*0 + 1*1, 0*1 + 1*(0 + 1)
so after all the math is done we end up with a call to the constructor with this
FibMatrix(1,1)
now we return this to the calling power function and end up with this:
- Code: Select all
power(FibMatrix(1,1),n>>1)
now the bit shift (n>>1) leaves us with 1
so now we call the power function with a FibMatrix(1,1) object and 1.
now starts recursion and my head is spinning so I will stop for now.