I came across the following code snippet for fast exponentiation. I can see that it works correctly, but I do not understand the logic that the author used to code it up so concisely. I do know the fast exponentiation concept and the general code one finds for it that uses divide and conquer recursively. Although the code snippet below must be doing exactly that, I am not able to wrap my head around what logic the author used to code it.
Could someone please explain?
int fastExp(int base, int exponent ) {
int b = 1, a = base;
while(exponent > 0) {
if(exponent%2) {
b = b * a;
}
exponent /= 2;
a = a * a;
}
return b;
}