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

(*
    Filename: fact.fs
         Rapid factorial and fibonacci seq implementations
         by pattern matching and tail recursive call

    Compile: fsc fact.fs
    Execute: fact

    Date: 2010/07/20
    Author: phkim  pkim __AT__ scripts.pe.kr
*)

#light

let rec fact (n:int) : bigint =
    match n with
    | 0 | 1    -> 1I
    | k        -> (bigint k) * (fact (k-1))

let factorial n =
    let rec loop acc k =
          match k with
          | 0 -> acc
          | _ -> loop (acc*(bigint k)) (k - 1)
    loop 1I n

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

let a = 30000
let b = 200000
printfn "Factorial(%O) has %O digits" a ((sprintf "%O" (factorial a)).Length)
printfn "Fibonacci(%O) has %O digits" b ((sprintf "%O" (fibonacci b)).Length)
(*
    Expected result:
    Factorial(30000) has 121288 digits
    Fibonacci(200000) has 41798 digits
*)

 

 


 

Posted by Scripter
,