Java 如何反转 BigInteger?

发布于 2024-12-18 19:02:23 字数 195 浏览 2 评论 0原文

我需要反转 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

朕就是辣么酷 2024-12-25 19:02:23

使用 BigInteger.modInverse() ——它将做你想做的事情。

如果你阅读了 BigInteger.modInverse() 的文档(它执行相同的计算,但比您的代码更有效;事实上,BigInteger.modPow() 在求幂之前调用 modInverse() 来获取负输入),您将 看:

抛出:ArithmeticException - m <= 0,或者此 BigInteger 没有乘法逆模 m(即,此 BigInteger 不与 m 互质)。

如果您得到“BigInteger not invertible”,这意味着 x 和 p 不是相对质数,因此作为输入给出的数字 x 和 p 对没有数学上定义的逆。

可能性:

  • p 是素数,并且 x 是 0 或 p 的倍数
  • p 不是素数,并且 x 和 p 有公因数
  • p 不是正整数(0 或负数),这违反了 modPow( ) 和 modInverse()

Use BigInteger.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 presumably BigInteger.modPow() calls modInverse() for negative inputs before raising to a power), you'll see:

Throws: ArithmeticException - m <= 0, or this BigInteger has no multiplicative inverse mod m (that is, this BigInteger is not relatively prime to m).

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:

  • p is prime, and x is 0 or a multiple of p
  • p is not prime, and x and p have a common factor
  • p is not a positive integer (0 or negative), which violates the requirements of modPow() and modInverse()
笑红尘 2024-12-25 19:02:23

只需输入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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文