This is the fastest algorithm I could come up with for the Fibonacci sequence in Python. After coding a solution with
The function returns both
fibonacci(69) # [117669030460994, 263115950957276]
These identities serve as the basis for the algorithm.
$F_{2n} = F_nL_n$ $L_{2n} = L_n^2-2(-1)^n$ $2F_{n+1} = F_n+L_n$ $2L_{n+1} = 5F_n+L_n$
Any Fibonacci number
- If
$n$ is zero, return the base cases$F_0$ and$L_0$ . - If
$n$ is odd, make it even by calculating$F_{n-1}$ and$L_{n-1}$ . - If
$n$ is even, halve it by calculating$F_{\frac{n}{2}}$ and$L_{\frac{n}{2}}$ .
Halving
These steps correlate with the binary representation of
-
0
$100$ -
0
$50$ -
1
$25, 24$ -
0
$12$ -
0
$6$ -
1
$3, 2$ -
1
$1, 0$