Skip to content

Big integers and rationals in OCaml with zarith ​

In Basthon, OCaml is compiled to JavaScript and its integers are 32 bits: max_int is 2,147,483,647 and the factorial of 13 already overflows. The zarith library brings integers of arbitrary size (Z module) and exact rationals (Q module):

ocaml
#require "zarith";;

let rec fact n = if n = 0 then Z.one else Z.mul (Z.of_int n) (fact (n - 1));;
fact 100;;

Z.probab_prime Z.(~$2 ** 127 - ~$1) 25;;
Q.(of_ints 1 10 + of_ints 2 10);;

GCD and Bézout's identity, modular inverse and exponentiation, primality tests: everything is there for arithmetic, up to a miniature RSA written in a few lines in the example notebook. Values are shown directly in the toplevel, and computations stay fast thanks to JavaScript's big integers (BigInt).

Play with it!

A miniature RSA with zarith