2 (** {1 Russian peasant multiplication}
4 Multiply two integers a and b using only addition, multiplication by 2,
7 Note: this is exactly the same algorithm as exponentiation by squaring
8 with power/*/1 being replaced by */+/0.
11 module BinaryMultiplication
16 let binary_mult (a b: int) : int
18 ensures { result = a * b }
24 invariant { !z + !x * !y = a * b }
26 if !y % 2 = 1 then z := !z + !x;
34 (** Now using machine integers.
36 Assuming that the product fits in machine integers, we can still
37 verify the code. The only exception is when `a*b = min_int`.
39 The code below makes no assumption on the sign of `b`.
40 Instead, it uses the fact that `!y % 2` has the sign of `!y`
41 so that `!x` is either added to or subtracted from the result.
44 module BinaryMultiplication63
51 let binary_mult (a b: int63) : int63
52 requires { min_int < a * b <= max_int }
53 ensures { result = a * b }
58 invariant { if a*b >= 0 then !x * !y >= 0 && !z >= 0
59 else !x * !y <= 0 && !z <= 0 }
60 invariant { !z + !x * !y = a * b }
62 z := !z + !x * (!y % 2);
64 (* be careful not to make the very last multiplication *)
65 if !y <> 0 then x := 2 * !x