You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BigInteger调用modInverse方法报数值不可逆错误原因排查

报错根因

BigInteger.modInverse() 触发不可逆报错的核心原因不是phi为负,而是调用方与参数模值不互质,即两者的最大公约数不等于1,这是模逆存在的数学前提。

你提供的测试用例报错原因

你的代码中phi计算结果为(3-1)*(11-1) = 20,e取值为4,两者的最大公约数为4,不满足互质要求,因此不存在模逆,调用方法必然抛出异常。

修复方案
  • 若你是实现RSA加密逻辑,选择公钥e时必须保证e与phi互质,通用常用值为65537;计算模逆前可先加前置校验避免报错:e.gcd(phi).equals(BigInteger.ONE)
  • 测试时可将e取值改为3,此时gcd(3,20)=1,可正常得到模逆结果7,验证3*7 mod 20 = 1符合模逆定义。

修改后可运行的测试代码如下:

BigInteger n = new BigInteger("33");  //p = 3 * 11;
BigInteger e = new BigInteger("3");
BigInteger p = new BigInteger("3");
BigInteger q = new BigInteger("11");
BigInteger phi = (p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)));
// 前置校验逻辑
if (e.gcd(phi).equals(BigInteger.ONE)) {
    BigInteger d = e.modInverse(phi);
    System.out.println(d); // 输出7
} else {
    System.out.println("e与phi不互质,不存在模逆");
}
官方规则说明

modInverse() 返回值为 this^{-1} mod m,仅当当前BigInteger与m互质时存在合法结果,否则抛出ArithmeticException。

内容的提问来源于stack exchange,提问作者user14370029

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 19:54:03