exception Input_Negativo

let mul (a,b,c,d) (e,f,g,h) =
  (a*e + b*g, a*f + b*h, c*e + d*g, c*f+d*h)
 
let rec pow a n =
  if n=0 then (1,0,0,1) (*ID matrix*)
  else if n=1 then a else
    let b = pow a (n/2) in
    if (n mod 2) = 0 then mul b b else mul a (mul b b)
                                           
let fib n =  if n<0 then raise Input_Negativo else 
  let (x,_,_,_) = (pow (1, 1, 1, 0) n) in x
 
let () =
  let n = int_of_string Sys.argv.(1) in 
    Printf.printf "fib %d = %d\n" n  (fib n)

This document was generated using caml2html