While looking into matrix exponentiation, I came across fast doubling and the implementation below. I have the following questions:
Why does the for loop iterate down from 31 to 0?
What is the purpose of masking n by i in the conditional?
private static BigInteger Fibonacci(int n) {
BigInteger a = BigInteger.Zero;
BigInteger b = BigInteger.One;
for (int i = 31; i >= 0; i--) {
BigInteger d = a * (b * 2 - a);
BigInteger e = a * a + b * b;
a = d;
b = e;
if ((((uint)n >> i) & 1) != 0) {
BigInteger c = a + b;
a = b;
b = c;
}
}
return a;
}
Please link any references or literature that could help me understand the topic in depth.
Cheers!