functional-programmingocaml

Is there any way to optimize this function and make it faster?


is there a way to optimize this? It is taking way too long to run

let counter2 = ref 0

let rec s2 num = 
  counter2 := !counter2 + 1;
  match num with
  | 0 -> 1
  | 1 -> 2
  | _ -> (((((6*num)-3) * (s2 (num-1))) / (num+1))) - (((num-2)* (s2 (num-2))/(num+1)))

Solution

  • Here is the highly recursive definition of the Fibonacci sequence:

    let rec fib n = 
      if n < 2 then n 
      else fib (n - 2) + fib (n - 1)
    

    Here is the not so recursive definition of the Fibonacci sequence.

    let nfib n =
      let rec helper pprev prev i =
        if i = n then
          pprev + prev
        else
          helper prev (pprev + prev) (i + 1)
      in
      if n < 2 then n 
      else helper 0 1 2
    

    Here is a function for timing things:

    let time f x =
      let st = Unix.gettimeofday () in
      let res = f x in
      Printf.printf "%f seconds\n" (Unix.gettimeofday () -. st);
      res
    

    Here are times for the fib and nfib functions:

    # time fib 42;;
    7.694294 seconds
    - : int = 267914296
    # time nfib 42;;
    0.000002 seconds
    - : int = 267914296