Josephus Problem in OCaml

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

Welcome to the Josephus Problem 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 ( let* ) = Option.bind

let josephus n k =
  let rec aux i acc = if i > n then acc else aux (i + 1) ((k + acc) mod i) in
  1 + aux 2 0

let parse_args argv =
  match argv with
  | [| _; n; k |] ->
      let* parsed_n = int_of_string_opt n in
      let* parsed_k = int_of_string_opt k in
      Some (parsed_n, parsed_k)
  | _ -> None

let () =
  match parse_args Sys.argv with
  | Some (n, k) when n > 0 && k >= 0 ->
      print_endline (string_of_int (josephus n k))
  | _ ->
      print_endline
        "Usage: please input the total number of people and number of people \
         to skip."

Josephus Problem 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.