ocaml: phase 5.1 fib_doubling.ml baseline (Fibonacci by doubling, fib(40) = 102334155)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
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.
This commit is contained in:
@@ -25,6 +25,7 @@
|
||||
"expr_eval.ml": 16,
|
||||
"expr_simp.ml": 22,
|
||||
"factorial.ml": 3628800,
|
||||
"fib_doubling.ml": 102334155,
|
||||
"fib_mod.ml": 391360,
|
||||
"fraction.ml": 7,
|
||||
"frequency.ml": 5,
|
||||
|
||||
14
lib/ocaml/baseline/fib_doubling.ml
Normal file
14
lib/ocaml/baseline/fib_doubling.ml
Normal file
@@ -0,0 +1,14 @@
|
||||
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
|
||||
@@ -407,6 +407,12 @@ _Newest first._
|
||||
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
|
||||
'a tree`) with insert + in-order traversal. Tests parametric ADT,
|
||||
recursive match, List.append, List.fold_left.
|
||||
- 2026-05-09 Phase 5.1 — fib_doubling.ml baseline (Fibonacci by
|
||||
doubling, fib(40) = 102334155). Uses the identity F(2k) = F(k) *
|
||||
(2*F(k+1) - F(k)) and F(2k+1) = F(k)^2 + F(k+1)^2 to compute fib
|
||||
in O(log n) recursive depth. Returns a tuple (F(n), F(n+1)) at
|
||||
each step. fib(40) = 102334155 fits in JS safe-int (< 2^53). 86
|
||||
baseline programs total.
|
||||
- 2026-05-09 Phase 5.1 — merge_two.ml baseline (merge two sorted
|
||||
lists, length*sum = 9*49 = 441). Standard two-finger merge with
|
||||
nested match-in-match. Used as a building block in merge_sort.ml
|
||||
|
||||
Reference in New Issue
Block a user