Computing
| Method | Time | Use |
|---|---|---|
| Iteration | ||
| Matrix power | ||
| Fast doubling | same, ~2× faster | |
| Binet’s formula | inexact beyond |
Matrix form
Fast doubling — the better method
pair<long long,long long> fib(long long n, long long MOD) { // returns {F(n), F(n+1)}
if (n == 0) return {0, 1};
auto [a, b] = fib(n >> 1, MOD);
long long c = a * ((2 * b % MOD - a + MOD) % MOD) % MOD;
long long d = (a * a + b * b) % MOD;
return (n & 1) ? make_pair(d, (c + d) % MOD) : make_pair(c, d);
}Half the multiplications of the matrix version, and no matrix struct.
Identities worth knowing
| Identity | |
|---|---|
| the addition formula | |
| strong divisibility | |
| corollary | |
| Cassini’s identity | |
| Binet, | |
| grows by a factor per step | |
the last one fitting in long long |
The strong divisibility property is the most useful — it turns questions about common factors of Fibonacci numbers into questions about of indices.
Pisano period
is periodic with period , the Pisano period.
| Fact | |
|---|---|
| , with equality iff | |
| is multiplicative over coprime factors: | |
| (conjecturally always) | |
| , , | |
| For : | |
| For : |
So for astronomically large reduces to — though fast doubling usually makes that unnecessary.
Zeckendorf representation
Every positive integer has a unique representation as a sum of non-consecutive Fibonacci numbers.
Greedy: repeatedly subtract the largest Fibonacci number that fits. This gives a “Fibonacci base” that appears in:
- Wythoff’s game — the losing positions are ;
- Fibonacci coding (a self-delimiting variable-length code);
- problems asking for a representation with no two adjacent terms.
Where Fibonacci shows up
| Problem | Why |
|---|---|
| Count binary strings with no two adjacent 1s | |
| Tile a board with dominoes | |
| Climbing stairs, 1 or 2 at a time | |
| Number of subsets of with no two consecutive | |
| Worst case of the Euclidean algorithm | consecutive Fibonacci inputs |
| Golden section search | ratio |
| AVL tree minimum size at height | Fibonacci-like |
| Wythoff’s game | Zeckendorf / |
Generalisations
- Lucas numbers : same recurrence, , . Related by and .
- Tribonacci / -bonacci: by matrix power, or by Bostan-Mori.
- General linear recurrences: see Linear Recurrences.
See also: Linear Recurrences · Matrix Exponentiation · Euclidean Algorithm