Problem (Fibonacci, 1202). A pair of rabbits matures in one month and then produces a new pair every month. Starting with one newborn pair, how many pairs after months? :
pair<long long, long long> fibPair(long long n, long long m) { // (F(n), F(n+1)) mod m, fast doubling
if (n == 0) return {0, 1 % m};
auto [a, b] = fibPair(n / 2, m);
long long c = a * ((2 * b - a + m) % m) % m, d = (a * a + b * b) % m;
return n % 2 ? make_pair(d, (c + d) % m) : make_pair(c, d);
}
long long pisano(long long m) { // period of F mod m (m >= 2), at most 6m
long long a = 0, b = 1;
for (long long i = 1; i <= 6 * m; i++) { long long t = (a + b) % m; a = b; b = t; if (a == 0 && b == 1) return i; }
return -1;
}| Fact | Statement |
|---|---|
| fast doubling | , : |
| matrix form | |
| Pisano period | is periodic with period : , |
| closed form | (Binet) |
Proof: fast doubling and the Pisano period
From the matrix identity, ; comparing entries gives and . Periodicity. The pair takes at most values, and the map to the next pair is invertible (), so the sequence of pairs is purely periodic and returns to . The bound is a known theorem (equality for ). Checked against the iterative recurrence for several moduli and the periods , , .