Problems > Fibonacci, Astronomically > Editorial

Fibonacci, Astronomically — Solution & Editorial

Back to the Problem

Fast doubling: F(2k) = F(k)[2F(k+1)−F(k)] and F(2k+1) = F(k)2+F(k+1)2, recursing on N/2 (equivalently, 2×2 matrix power).

Complexity: O(log N)

Watch out: Beware negative intermediate (2F(k+1)−F(k)) — normalize mod p before multiplying.