Skip to content

Commit

Permalink
Euclid now returns a record
Browse files Browse the repository at this point in the history
  • Loading branch information
ghuysmans committed Aug 23, 2019
1 parent 665362a commit 3572071
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 5 deletions.
11 changes: 7 additions & 4 deletions lib/numbers.ml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ module type S = sig
module N : Concrete
val modpow: N.t -> N.t -> m:N.t -> N.t
val fermat: N.t -> bool
val euclid: N.t -> N.t -> N.t * N.t * N.t
type e = {r: N.t; u: N.t; v: N.t}
val euclid: N.t -> N.t -> e
val gcd: N.t -> N.t -> N.t
val inv: N.t -> m:N.t -> N.t
val random: bits:int -> N.t
Expand Down Expand Up @@ -75,24 +76,26 @@ module Make (N: Concrete) = struct
in
f 200

type e = {r: N.t; u: N.t; v: N.t}

let euclid a b = (* taken from Wikipedia *)
let open N in
let rec f r u v r' u' v' =
if r' = zero then
r (* gcd *), u, v
{r; u; v}
else
let q = r / r' in
f r' u' v' (r - q * r') (u - q * u') (v - q * v')
in
f a one zero b zero one

let gcd a b =
let r, _, _ = euclid a b in
let {r; _} = euclid a b in
r

let inv x ~m =
let open N in
let r, x', _ = euclid x m in
let {r; u = x'; _} = euclid x m in
if r = one then
if x' < zero then x' + m else x'
else
Expand Down
5 changes: 4 additions & 1 deletion lib/numbers.mli
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ module type S = sig
module N : Concrete
val modpow: N.t -> N.t -> m:N.t -> N.t
val fermat: N.t -> bool
val euclid: N.t -> N.t -> N.t * N.t * N.t
type e = {r: N.t; u: N.t; v: N.t}
val euclid: N.t -> N.t -> e
(** [euclid a b] returns an [e] such that $r = au + bv = gcd(a, b)$ *)

val gcd: N.t -> N.t -> N.t
val inv: N.t -> m:N.t -> N.t
val random: bits:int -> N.t
Expand Down

0 comments on commit 3572071

Please sign in to comment.