자리수가 매우 긴 정수(큰 정수, big integer)를 계산하려면
C/C++ 언어로는 gmp 또는 mpir 라이브러리를 쓰면 되고
Java 언어로는 java.math.BigInteger 클래스를 사용하면 되고,
C# 언어로는 System.Numerics.BigInteger 클래스를 사용하면 되고,
Python 언어로는 long 타입(Python 이 자체적으로 알아서 int 타입과 long 타입을 자동 변환함)을쓰면 되고,
Haskell 언어로는 (Int 타입 대신) Integer 타입을 쓰면 된다.
F# 언어의 경우에는 F 샤프 를 참조한다,
그렇다면 OCaml 언어로는 big integer 계산을 어떻게 할까?
답은 의외로 간단하다. 이미 lib 폴더에 설치되어 있는 라이브러리 nums.cma 를 불러 쓰면 된다.
toplevel 에서 사용하거니 ocaml 로 스크립트를 실행할 때는 디렉티브 구문 #load "nums,cma" 를 사용하면 된다. 그러나 ocamlc 명령을 컴파일할 때는 이 디렉티브가 통하지 않으니 이 디렉토리 구문을 주석 처리 하고 컴파일하는 명령줄에 nums.cma 를 추가하면 된다. 이 디렉티브가 없더라도 ocaml 명령으로 스크립트를 실행하는 명령줄에 nums.cma 를 추가하면 된다. 명령 줄에 이를 추가하지 않으면, 정의되지 않은 전역적인(global) Num 을 참조한다는 에러 메시지가 뜬다.
Error: Reference to undefined global `Num'
OCaml 언어에서 big integer 타입의 사칙 연산 기호는 +, -, *, / 가 아니라 +/, -/. */. // 이다. (연산 기호 모두 / 문자가 하나씩 더 붙는다.)
1) 스크립트로 실행하기
프롬프트> ocaml nums.cma calcBigFactorial.ml
2) 컴파일한 후 실행하기
프롬프트> ocamlc -o calcBigFactorial.exe nums.cma calcBigFactorial.ml
프롬프트> calcBigFactorial
* Filename: calcBigFactorial.ml
*
* Purpose: Caculation big integers and big rationals with OCaml language.
*
* Execute: ocaml nums.cma calcBigFactorial.ml
*
* Or
*
* Compile: ocamlc -o calcBigFactorial.exe nums.cma calcBigFactorial.ml
* Execute: calcBigFactorial.exe
*
* See: http://caml.inria.fr/resources/doc/faq/core.en.html
* Date: 2013. 1. 30.
*)
(* #load "nums.cma";; *) (* This line works in the toplevel of OCaml *)
open Num;;
open Format;; (* This is reauired for printf *)
(* let print_num ff n = fprintf ff "%s" (string_of_num n);; *)
let rec fact n =
if n <= 0 then (num_of_int 1) else num_of_int n */ (fact (n - 1));;
let x = 100
in
printf "%d! = %s\n" x (string_of_num (fact x));;
(*
Output:
100! = 9332621544394415268169923885626670049071596826438162146859296389521759999
32299156089414639761565182862536979208272237582511852109168640000000000000000000
00000
*)
'프로그래밍 > OCaml' 카테고리의 다른 글
문자열 거꾸로 하기 with OCaml (0) | 2013.02.02 |
---|---|
손으로 만드는 나눗셈 계산표 with OCaml (0) | 2013.02.01 |
7비트 ASCII 코드표 만들기 예제 with OCaml (0) | 2013.01.29 |
OCaml 에 Extlib 설치하고 사용하는 예 (0) | 2013.01.29 |
진법(radix) 표 만들기 예제 with OCaml (0) | 2013.01.28 |