2 (** Greatest common divisor, using the Euclidean algorithm *)
4 module EuclideanAlgorithm
9 let rec euclid (u v: int) : int
11 requires { u >= 0 /\ v >= 0 }
12 ensures { result = gcd u v }
21 module EuclideanAlgorithmIterative
27 let euclid (u0 v0: int) : int
28 requires { u0 >= 0 /\ v0 >= 0 }
29 ensures { result = gcd u0 v0 }
34 invariant { !u >= 0 /\ !v >= 0 }
35 invariant { gcd !u !v = gcd u0 v0 }
51 lemma even1: forall n: int. 0 <= n -> even n <-> n = 2 * div n 2
52 lemma odd1: forall n: int. 0 <= n -> not (even n) <-> n = 2 * div n 2 + 1
53 lemma div_nonneg: forall n: int. 0 <= n -> 0 <= div n 2
57 lemma gcd_even_even: forall u v: int. 0 <= v -> 0 <= u ->
58 gcd (2 * u) (2 * v) = 2 * gcd u v
59 lemma gcd_even_odd: forall u v: int. 0 <= v -> 0 <= u ->
60 gcd (2 * u) (2 * v + 1) = gcd u (2 * v + 1)
61 lemma gcd_even_odd2: forall u v: int. 0 <= v -> 0 <= u ->
62 even u -> odd v -> gcd u v = gcd (div u 2) v
63 lemma odd_odd_div2: forall u v: int. 0 <= v -> 0 <= u ->
64 div ((2*u+1) - (2*v+1)) 2 = u - v
66 let lemma gcd_odd_odd (u v: int)
67 requires { 0 <= v <= u }
68 ensures { gcd (2 * u + 1) (2 * v + 1) = gcd (u - v) (2 * v + 1) }
69 = assert { gcd (2 * u + 1) (2 * v + 1) =
70 gcd ((2*u+1) - 1*(2*v+1)) (2 * v + 1) }
72 lemma gcd_odd_odd2: forall u v: int. 0 <= v <= u ->
73 odd u -> odd v -> gcd u v = gcd (div (u - v) 2) v
75 let rec binary_gcd (u v: int) : int
77 requires { u >= 0 /\ v >= 0 }
78 ensures { result = gcd u v }
80 if v > u then binary_gcd v u else
83 if mod v 2 = 0 then 2 * binary_gcd (u / 2) (v / 2)
84 else binary_gcd (u / 2) v
86 if mod v 2 = 0 then binary_gcd u (v / 2)
87 else binary_gcd ((u - v) / 2) v
91 (** With machine integers.
92 Note that we assume parameters u, v to be nonnegative.
93 Otherwise, for u = v = min_int, the gcd could not be represented. *)
95 (* does not work with extraction driver ocaml64
96 module EuclideanAlgorithm31
101 let rec euclid (u v: int31) : int31
103 requires { u >= 0 /\ v >= 0 }
104 ensures { result = gcd u v }
114 module EuclideanAlgorithm63
119 let rec euclid (u v: int63) : int63
121 requires { u >= 0 /\ v >= 0 }
122 ensures { result = gcd u v }