#include int main() { int n, t1, t2, t, a, b, msb, temp, i; printf("Enter n: "); scanf("%d", &n); if (n == 0) { printf("Fibonacci = 0\n"); return 0; } a = 0; // F(0) b = 1; // F(1) // Find the highest set bit position msb = 0; temp = n; while (temp > 1) { temp >>= 1; msb++; } // Bottom-up doubling method for (i = msb; i >= 0; i--) { t1 = a * ((b << 1) - a); // F(2k) t2 = a * a + b * b; // F(2k+1) a = t1; b = t2; if ((n >> i) & 1) { // If bit is set int t = a + b; // move to next This moves from (F(2k),F(2k+1)) (F(2k),F(2k+1)) → (F(2k+1),F(2k+2))(F(2k+1),F(2k+2)). a = b; b = t; } } printf("Fibonacci = %d\n", a); return 0; } /* * Binary of 5 = 101 Highest bit index = 2 Loop steps (showing only a = F(k)): Start: (a,b) = (0,1) Bit 2: doubling → (0,1) → (0,1). Bit=1 → shift → (1,1) Bit 1: doubling → (1,1) → (1,2). Bit=0 → no shift Bit 0: doubling → (1,2) → (3,5). Bit=1 → shift → (5,8) Done: a = 5 = F(5). * */