(********************************************************************)
(*  OCaml code from the book ``Learn Programming with OCaml''       *)
(*  See https://usr.lmf.cnrs.fr/lpo/                                *)
(*                                                                  *)
(*  Sylvain Conchon and Jean-Christophe Filliâtre                   *)
(*  Copyright 2025 Université Paris-Saclay and CNRS                 *)
(*                                                                  *)
(*  Openly licensed via CC BY SA 4.0                                *)
(*  See https://creativecommons.org/licenses/by-sa/4.0/deed.en      *)
(********************************************************************)

(* Program 82 on page 349
   Arithmetic modulo m (multiplication and division) *)

  let mul x y =
    let r = ref 0 in
    for i = Sys.word_size - 4 downto 0 do
      r := add !r !r;
      if x land (1 lsl i) <> 0 then r := add !r y
    done;
    !r

  let div x y =
    let u, _, g = extended_gcd y m in
    if g <> 1 then invalid_arg "div";
    mul x (of_int u)

This document was generated using caml2html