當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。