Java如何反转BigInteger? [英] Java How to invert a BigInteger?
问题描述
我需要反转一个 BigInteger
.
假设我有 BigInteger x;
,并且我需要计算 x.modPow(new BigInteger(-1"),p)
.
Let's say i have BigInteger x;
and i need to calculate x.modPow(new BigInteger("-1"), p)
.
我收到以下错误: java.lang.ArithmeticException:BigInteger不可逆
.
推荐答案
使用 BigInteger.modInverse()
-它会做您想要的事情.
Use BigInteger.modInverse()
-- it will do what you want.
如果您阅读了 BigInteger.modInverse()
的文档(它执行相同的计算,但是比您的代码更有效;实际上大概是 BigInteger.modPow()
在提高功率之前调用 modInverse()
进行负输入),您将看到:
If you read the docs for BigInteger.modInverse()
(which performs the identical calculation, but more efficiently than your code; in fact presumably BigInteger.modPow()
calls modInverse()
for negative inputs before raising to a power), you'll see:
抛出:ArithmeticException-m< = 0,或者此BigInteger不具有乘法逆模m(即,该BigInteger相对于m而言不是素数).
Throws: ArithmeticException - m <= 0, or this BigInteger has no multiplicative inverse mod m (that is, this BigInteger is not relatively prime to m).
如果您得到"BigInteger不可逆",则意味着x和p不是相对质数,因此对于数学上定义为输入的x和p对没有逆.
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.
可能性:
- p是质数,x是0或p的倍数
- p不是素数,并且x和p具有一个公因数
- p不是正整数(0或负数),这违反了
modPow()
和modInverse()
的要求
这篇关于Java如何反转BigInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!