ocaml: phase 5.1 matrix_power.ml baseline (F(30) = 832040 via 2x2 matrix pow)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s

Fibonacci via repeated-squaring matrix exponentiation:

  [[1, 1], [1, 0]] ^ n = [[F(n+1), F(n)], [F(n), F(n-1)]]

Recursive O(log n) power:

  let rec mpow m n =
    if n = 0 then identity
    else if n mod 2 = 0 then let h = mpow m (n / 2) in mul h h
    else mul m (mpow m (n - 1))

Returns the .b cell after raising to the 30th power -> 832040 = F(30).

Tests record literal construction inside recursive function returns,
record field access (x.a etc), and pure integer arithmetic in the
matrix multiply.

165 baseline programs total.
This commit is contained in:
2026-05-10 23:18:26 +00:00
parent d1a4616ac4
commit 689438d12e
3 changed files with 29 additions and 0 deletions

View File

@@ -82,6 +82,7 @@
"list_ops.ml": 30,
"luhn.ml": 2,
"mat_mul.ml": 621,
"matrix_power.ml": 832040,
"max_path_tree.ml": 11,
"max_product3.ml": 300,
"max_run.ml": 5,

View File

@@ -0,0 +1,20 @@
type m22 = { a : int; b : int; c : int; d : int }
let mul x y =
{ a = x.a * y.a + x.b * y.c;
b = x.a * y.b + x.b * y.d;
c = x.c * y.a + x.d * y.c;
d = x.c * y.b + x.d * y.d }
let rec mpow m n =
if n = 0 then { a = 1; b = 0; c = 0; d = 1 }
else if n mod 2 = 0 then
let h = mpow m (n / 2) in mul h h
else
mul m (mpow m (n - 1))
;;
let fib_matrix = { a = 1; b = 1; c = 1; d = 0 } in
let r = mpow fib_matrix 30 in
r.b