Factorial in OCaml

Published on 17 May 2026 (Updated: 17 May 2026)

Welcome to the Factorial in OCaml page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

let factorial n =
  (* Use accumulator so OCaml can do tail call recursion *)
  let rec helper acc n =
    match n with 0 | 1 -> acc | n -> helper (acc * n) (n - 1)
  in
  helper 1 n

let parse_args argv =
  match argv with [| _; n |] -> int_of_string_opt n | _ -> None

let () =
  print_endline
    (match parse_args Sys.argv with
    | Some num when num >= 0 -> num |> factorial |> string_of_int
    | _ -> "Usage: please input a non-negative integer")

Factorial in OCaml was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.