(* Calcul matriciel

   Exponentiation rapide *)

(* Programme 83 page 333 *)

type matrix = int array array

let init_matrix n m f =
  Array.init n (fun i -> Array.init m (fun j -> f i j))

let id n =
  init_matrix n n (fun i j -> if i = j then 1 else 0)

let size a =
  (Array.length a, Array.length a.(0))

let mul a b =
  let n, p = size a in
  let q, m = size b in
  if q <> p then invalid_arg "mul";
  let product i j =
    let s = ref 0 in
    for k = 0 to p - 1 do s := !s + a.(i).(k) * b.(k).(j) done;
    !s
  in
  init_matrix n m product

(* C'est exactement le programme 80 page 328, avec id et mul à la place
   de 1 et * *)

let rec power x n =
  if n = 0 then
    id (Array.length x)
  else
    let y = power x (n/2) in
    if n mod 2 = 1 then mul x (mul y y) else mul y y

This document was generated using caml2html