Factorial: Difference between revisions

→‎{{header|OCaml}}: add bignum example
(→‎{{header|OCaml}}: add bignum example)
Line 3,992:
done;
!result</lang>
 
===Bignums===
All of the previous examples use normal OCaml ints, so on a 64-bit platform the factorial of 100 will be equal to 0, rather than to a 158-digit number.
 
The following code uses the Zarith package to calculate the factorials of larger numbers:
<lang ocaml>let rec factorial n =
let rec loop acc = function
| 0 -> acc
| n -> loop (Z.mul (Z.of_int n) acc) (n - 1)
in loop Z.one n
 
let () =
if not !Sys.interactive then
begin
Sys.argv.(1) |> int_of_string |> factorial |> Z.print;
print_newline ()
end</lang>
 
{{out}}
<pre>$ ocamlfind ocamlopt -package zarith zarith.cmxa fact.ml -o fact
$ ./fact 100
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000</pre>
 
=={{header|Octave}}==
Anonymous user