Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Uses the identities:
F(2k) = F(k) * (2 * F(k+1) - F(k))
F(2k+1) = F(k)^2 + F(k+1)^2
to compute Fibonacci in O(log n) recursive depth instead of O(n).
let rec fib_pair n =
if n = 0 then (0, 1)
else
let (a, b) = fib_pair (n / 2) in
let c = a * (2 * b - a) in
let d = a * a + b * b in
if n mod 2 = 0 then (c, d)
else (d, c + d)
Each call returns the pair (F(n), F(n+1)). fib(40) = 102334155 fits
in JS safe-int (< 2^53). Tests tuple returns with let-tuple
destructuring + recursion on n / 2.
86 baseline programs total.
15 lines
253 B
OCaml
15 lines
253 B
OCaml
let rec fib_pair n =
|
|
if n = 0 then (0, 1)
|
|
else
|
|
let (a, b) = fib_pair (n / 2) in
|
|
let c = a * (2 * b - a) in
|
|
let d = a * a + b * b in
|
|
if n mod 2 = 0 then (c, d)
|
|
else (d, c + d)
|
|
|
|
let fib n = let (f, _) = fib_pair n in f
|
|
|
|
;;
|
|
|
|
fib 40
|