File size: 1,176 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
/*@ Import Lean
import Algorithms.modular_power.lean.helper_lib
open scoped SimpleC
*/
/*@ Extern Coq
      (ModularPower : Z -> Z -> Z -> Z -> Prop)
      (ModularPowerProgress : Z -> Z -> Z -> Z -> Z -> Z -> Prop)
 */

int modular_power(int a, int b, int modulus)
/*@ Require
      0 <= a && a < modulus &&
      0 <= b &&
      2 <= modulus && modulus <= 46341 && emp
    Ensure
      0 <= __return && __return < modulus &&
      ModularPower(a, b, modulus, __return) && emp
 */
{
    int result = 1;

    /*@ Inv Assert
          0 <= a@pre && a@pre < modulus@pre &&
          0 <= b@pre &&
          modulus == modulus@pre &&
          2 <= modulus@pre && modulus@pre <= 46341 &&
          0 <= a && a < modulus@pre &&
          0 <= b && b <= b@pre &&
          0 <= result && result < modulus@pre &&
          0 <= a * a && a * a <= INT_MAX &&
          0 <= result * a && result * a <= INT_MAX &&
          ModularPowerProgress(a@pre, b@pre, modulus@pre,
            a, b, result) && emp
     */
    while (b > 0) {
        if (b % 2 == 1) {
            result = result * a % modulus;
        }
        a = a * a % modulus;
        b /= 2;
    }

    return result;
}