Java 如何反转 BigInteger?
我需要反转 BigInteger。
假设我有 BigInteger x;
并且我需要计算 x.modPow(new BigInteger("-1"), p)
。
我收到以下错误:java.lang.ArithmeticException:BigInteger 不可逆
。
I need to invert a BigInteger
.
Let's say i have BigInteger x;
and i need to calculate x.modPow(new BigInteger("-1"), p)
.
I receive the following error: java.lang.ArithmeticException: BigInteger not invertible
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用BigInteger.modInverse()
——它将做你想做的事情。如果你阅读了
BigInteger.modInverse()
的文档(它执行相同的计算,但比您的代码更有效;事实上,BigInteger.modPow()
在求幂之前调用modInverse()
来获取负输入),您将 看:如果您得到“BigInteger not invertible”,这意味着 x 和 p 不是相对质数,因此作为输入给出的数字 x 和 p 对没有数学上定义的逆。
可能性:
modInverse()
UseBigInteger.modInverse()
-- it will do what you want.If you read the docs for
BigInteger.modInverse()
(which performs the identical calculation, but more efficiently than your code; in fact presumablyBigInteger.modPow()
callsmodInverse()
for negative inputs before raising to a power), you'll see:If you're getting "BigInteger not invertible" this means that x and p are not relatively prime, so there is no mathematically defined inverse for the pair of numbers x and p given as input.
Possibilities:
modPow()
andmodInverse()
只需输入
return BigInteger.ZERO
即可。任何时候你对一个大于一的数字进行反转,你的结果都会在 0 和 1 之间。当这个数字表示为整数时,它最终会是 0...Just put
return BigInteger.ZERO
. Any time you invert a number greater than one, your result is between 0 and 1. When this number is represented as an integer, it ends up being 0...