Java中的Java .math.BigInteger.modInverse() 方法
先决条件: BigInteger 基础
modPow() 方法返回它的模乘逆模 m。如果 m <= 0 或 this 没有乘法逆模 m(即 gcd(this, m) != 1),此方法将引发 ArithmeticException。
句法:
public BigInteger modInverse(BigInteger m)
参数: m – 模数。
返回值:此方法返回一个 BigInteger 对象,其值为 ((this)^(-1) mod m)。
例外:
- ArithmeticException – m <= 0,或者这个 BigInteger 没有乘法逆模 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
方案二:
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: Java Java.math.BigInteger)