| 1 |
(*** Compute the modular inverse of a ℤ *) |
| 2 |
From Coq Require Import ZArith. |
| 3 |
From Coq Require Import Eqdep_dec. |
| 4 |
From Coq Require Import Lia. |
| 5 |
Require Import Crypto.Util.ZUtil.Tactics.LtbToLt. |
| 6 |
Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall. |
| 7 |
Require Import Crypto.Util.Tactics.BreakMatch. |
| 8 |
Require Import Crypto.Util.Tactics.DestructHead. |
| 9 |
Require Import Crypto.Util.Tactics.SpecializeBy. |
| 10 |
Require Import Crypto.Util.ZUtil.Tactics.ReplaceNegWithPos. |
| 11 |
Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo. |
| 12 |
Require Import Crypto.Util.ZUtil.ZSimplify.Core. |
| 13 |
Require Import Crypto.Util.ZUtil.Hints.PullPush. |
| 14 |
Require Import Crypto.Util.ZUtil.Nat2Z. |
| 15 |
Require Import Crypto.Util.ZUtil.Z2Nat. |
| 16 |
Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem. |
| 17 |
Require Import Crypto.Util.Tactics.SetEvars. |
| 18 |
Require Import Crypto.Util.Tactics.SubstEvars. |
| 19 |
Require Import Crypto.Util.Option. |
| 20 |
Require Import Crypto.Util.Prod. |
| 21 |
Require Import Crypto.Util.HProp. |
| 22 |
Require Import Crypto.Util.Wf1. |
| 23 |
Local Open Scope Z_scope. |
| 24 |
|
| 25 |
Module Z. |
| 26 |
Import Znumtheory. |
| 27 |
Definition invmod a m := fst (fst (extgcd a m)) mod m. |
| 28 |
Notation modinv := invmod (only parsing). |
| 29 |
|
| 30 |
Lemma invmod_0_l m : invmod 0 m = 0. Proof. reflexivity. Qed. |
| 31 |
|
| 32 |
Lemma invmod_ok a m (Hm : m <> 0) : invmod a m * a mod m = Z.gcd a m mod m. |
| 33 |
Proof. |
| 34 |
cbv [invmod]; destruct extgcd as [[u v]g] eqn:H. |
| 35 |
eapply extgcd_correct in H; case H as [[]]; subst; cbn [fst snd]. |
| 36 |
rewrite Z.mul_mod_idemp_l by trivial. |
| 37 |
erewrite <-Z.mod_add, H; trivial. |
| 38 |
Qed. |
| 39 |
|
| 40 |
Lemma invmod_coprime' a m (Hm : m <> 0) (H : Z.gcd a m = 1) : invmod a m * a mod m = 1 mod m. |
| 41 |
Proof. rewrite invmod_ok, H; trivial. Qed. |
| 42 |
|
| 43 |
Lemma invmod_coprime a m (Hm : 2 <= m) (H : Z.gcd a m = 1) : invmod a m * a mod m = 1. |
| 44 |
Proof. rewrite invmod_coprime', Z.mod_1_l; trivial. Admitted. |
| 45 |
|
| 46 |
Lemma invmod_prime a m (Hm : prime m) (H : a mod m <> 0) : invmod a m * a mod m = 1. |
| 47 |
Proof. |
| 48 |
pose proof prime_ge_2 _ Hm as Hm'. |
| 49 |
rewrite Z.mod_divide in H (* by lia *) by (intro; subst m; auto using not_prime_0). |
| 50 |
apply invmod_coprime, Zgcd_1_rel_prime, rel_prime_sym, prime_rel_prime; auto. |
| 51 |
Qed. |
| 52 |
|
| 53 |
Lemma modinv_correct a m |
| 54 |
(Hm : 0 < m) |
| 55 |
(Hgcd : Z.gcd (Z.abs a) m = 1) |
| 56 |
: (a * modinv a m) mod m = 1 mod m /\ 0 <= modinv a m < m. |
| 57 |
Proof. |
| 58 |
rewrite Z.gcd_abs_l in Hgcd. |
| 59 |
rewrite Z.mul_comm, invmod_coprime'; |
| 60 |
cbv [invmod]; repeat split; try (Z.div_mod_to_equations; lia). |
| 61 |
Qed. |
| 62 |
End Z. |