Java.math.BigInteger.modInverse()方法在Java中的应用
前提是: 大整数基础知识
modPow()方法返回this的模块化乘法逆,mod m。如果m<=0或者this没有mod m的乘法逆(即gcd(this, m) !=1),该方法会抛出一个ArithmeticException。
语法
public BigInteger modInverse(BigInteger m)
参数: m – 模数。
返回值: 该方法返回一个BigInteger对象,其值为((this)^(-1)mod m)。
异常
- ArithmeticException – m <= 0, 或者这个BigInteger没有乘法逆数mod m (也就是说,这个BigInteger不是相对于m的素数)。
以下程序说明了BigInteger.modInverse()方法。
程序1 :
import java.math.*;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// create 2 BigInteger objects
BigInteger biginteger1, biginteger2, result;
// Initialize all BigInteger Objects
biginteger1 = new BigInteger("8");
biginteger2 = new BigInteger("21");
// perform modInverse operation on biginteger1 using biginteger2.
result = biginteger1.modInverse(biginteger2);
String expression = biginteger1 + " ^ -1 % "
+ biginteger2 + " = " + result;
// print result value
System.out.println(expression);
}
}
输出:
8 ^ -1 % 21 = 8
程序2 :
import java.math.*;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// create 2 BigInteger objects
BigInteger biginteger1, biginteger2, result;
// Initialize all BigInteger Objects
biginteger1 = new BigInteger(88882);
biginteger2 = new BigInteger(22224);
// perform modInverse operation on biginteger1 using biginteger2.
result = biginteger1.modInverse(biginteger2);
String expression = biginteger1 + " ^ -1 % "
+ biginteger2 + " = " + result;
// print result value
System.out.println(expression);
}
}
输出:
Exception in thread "main" java.lang.ArithmeticException: BigInteger not invertible.
at java.math.MutableBigInteger.modInverse(Unknown Source)
at java.math.MutableBigInteger.mutableModInverse(Unknown Source)
at java.math.BigInteger.modInverse(Unknown Source)
at BigInteger.GFG2.main(GFG2.java:23)
**参考: ** https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#modInverse(java.math.BigInteger).