当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Java.math.BigInteger.modInverse()用法及代码示例


先决条件:BigInteger基础

modPow()方法返回此模m的模乘逆。如果m> = 0或没有乘法逆模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

程序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)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Java.math.BigInteger.modInverse() method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。