From 89a258359f34d452a07539556bedff0d596f7b7c Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Fri, 18 Jul 2025 00:11:25 +0800 Subject: [PATCH] feat: mod inv --- src/main/java/me/hatter/math/ModularInv.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/me/hatter/math/ModularInv.java b/src/main/java/me/hatter/math/ModularInv.java index bd7c7f2..11b1f6d 100644 --- a/src/main/java/me/hatter/math/ModularInv.java +++ b/src/main/java/me/hatter/math/ModularInv.java @@ -26,13 +26,16 @@ public class ModularInv { for (long j = 1; j < 10000; j++) { BigInteger a = BigInteger.valueOf(i); BigInteger p = BigInteger.valueOf(j); + // gcd(a, p) = 1 if (!a.gcd(p).equals(BigInteger.ONE)) { continue; } + // a^-1 mod p BigInteger x = a.modInverse(p); BigInteger y = modularInv(a, p); - System.out.println(Arrays.asList(a, p, a.modInverse(p), modularInv(a, p))); - if (!y.equals(x)) { + BigInteger z = a.modPow(Phi.phi(p).subtract(BigInteger.ONE), p); + System.out.println(Arrays.asList(a + "^-1 mod " + p, x, y, z)); + if (!y.equals(x) || !y.equals(z)) { throw new RuntimeException(); } }