* 꼬리 재귀호출과 패턴 매칭을 이용하여 구현한 팩토리얼과 피보나치 수열 계산
(*
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
*)
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
*)
'프로그래밍 > F#' 카테고리의 다른 글
F# 윈도우 애플리케이션에서 마우스 이벤트 감지하기 2 (0) | 2010.08.11 |
---|---|
F# 윈도우 애플리케이션에서 마우스 이벤트 감지하기 (0) | 2010.07.23 |
int 타입과 bigint 타입 간 상호 변환 with F# (0) | 2010.07.18 |
Pollard's rho method 소개: 정수의 인수분해(factorizing integers) with F# (0) | 2010.07.17 |
스트링 리스트에서 스트링 찾기(find) with F# (0) | 2010.07.16 |