|
|
|
|
|
by sbi
4567 days ago
|
|
The "right" way to generate Fibonacci numbers is not via the closed form, but by exponentiation of the matrix A = [0 1; 1 1] that defines Fibonacci numbers as an element of its endomorphism ring Z[x]/(x^2 - x - 1). This doesn't rely on explicitly computing the eigenvalues of A and scales well to more complex recursions. Sample Haskell: fib :: Integer -> Integer
fib n = fst . loop (0, 1) base . abs $ n
where pmul (a, b) (c, d) = ((a + b)*(c + d) - b*d, b*d + a*c)
base = if n >= 0 then (1, 0) else (1, -1)
loop acc sq m
| m == 0 = acc
| m `mod` 2 == 0 = loop acc (pmul sq sq) (m `div` 2)
| otherwise = loop (pmul sq acc) (pmul sq sq) (m `div` 2)
|
|