File size: 1,215 Bytes
bff4ec7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*@ Import Lean
import AUXLib.Arithmetic
import SimpleC.SL.SeparationLogic
open scoped SimpleC
*/
/*@ Extern Coq (Zgcd: Z -> Z -> Z) */

/*
 * The verified exgcd case supplies this interface.  In particular, x and y
 * are Bezout coefficients when the call returns.
 */
int exgcd(int a, int b, int *x, int *y)
/*@ Require
      INT_MIN < a && a <= INT_MAX &&
      INT_MIN < b && b <= INT_MAX &&
      has_int_permission(x) * has_int_permission(y)
    Ensure
      __return == Zgcd(a, b) &&
      a * (*x) + b * (*y) == Zgcd(a, b)
*/;

/*
 * Return the canonical representative of the inverse of a modulo modulus.
 * The precondition restricts this small example to the usual coprime,
 * positive inputs for which an inverse exists.
 */
int modular_inverse(int a, int modulus)
/*@ Require
      1 < modulus && 0 < a && a < modulus && Zgcd(a, modulus) == 1 && emp
    Ensure
      0 <= __return && __return < modulus &&
      exists k, a * __return + modulus * k == 1 && emp
*/
{
    int x;
    int y;
    int g = exgcd(a, modulus, &x, &y);

    /* The precondition and the exgcd contract imply g == 1. */
    int inverse = x % modulus;
    if (inverse < 0) {
        inverse += modulus;
    }
    return inverse;
}