* 꼬리 재귀호출과 패턴 매칭을 이용하여 구현한 팩토리얼과 피보나치 수열 계산

(*
    Filename: fact.ml

         Rapid factorial and fibonacci seq implementations
         by pattern matching and tail recursive call

    Execute: ocaml nums.cma fact.ml
      or
    Compile: ocamlc -o fact.exe nums.cma fact.ml
    Execute: fact

    Date: 2013. 2. 6.
    Author: pkim __AT__ scripts.pe.kr
*)

open Printf
open Num

let bignum x = num_of_int x ;;
let to_string x = string_of_num x ;;

let rec fact n =
    match n with
    | 0 | 1    -> bignum 1
    | k        -> (bignum k) */ (fact (k-1)) ;;

let factorial n =
    let rec loop acc k =
          match k with
          | 0 -> acc
          | _ -> loop (acc */ (bignum k)) (k - 1)
    in
    loop (bignum 1) n  ;;

let fibonacci n =
    let rec loop a b k =
          match k with
          | 0 -> a
          | _ -> loop (a +/ b) a (k - 1)
    in
    loop (bignum 1) (bignum 0) n ;;

let a = 30000 in
let b = 200000 in
printf "Factorial(%d) has %d digits\n" a (String.length (sprintf "%s" (to_string (factorial a)))) ;
printf "Fibonacci(%d) has %d digits\n" b (String.length (sprintf "%s" (to_string (fibonacci b))))

(*
Expected result:
Factorial(30000) has 121288 digits
Fibonacci(200000) has 41798 digits
*)

 

Posted by Scripter
,