Java How to invert a BigInteger?

跟風遠走 提交于 2019-12-12 10:54:54

问题


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.


回答1:


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()



回答2:


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...



来源:https://stackoverflow.com/questions/8318018/java-how-to-invert-a-biginteger

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!