Java BigInteger Class | modPow() Method with Example

BigInteger Class modPow() method: Here, we are going to learn about the modPow() method of BigInteger Class with its syntax and example.
Submitted by Preeti Jain, on May 11, 2020

BigInteger Class modPow() method

  • modPow() method is available in java.math package.
  • modPow() method is used to calculate the mod pow by using the (this BigInteger) raised to the power of the first given argument (exp) mod the second given parameter [i.e. (this BigInteger) pow (exp) mod (BigDecimal val) ].
  • modPow() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • modPow() method may throw an exception at the time of returning mod pow.
    ArithmeticException: This exception may throw when the given parameter holds value 0 or negative.

Syntax:

    public BigInteger modPow(BigInteger exp, BigInteger val);

Parameter(s):

  • BigInteger exp – represents the object by which to calculate mod pow.
  • BigInteger val – represents the exponent raised to the power of this BigInteger.

Return value:

The return type of this method is BigInteger, it returns BigInteger that holds the value by using [ (this BigInteger) pow (exp) mod (BigInteger val) ].

Example:

// Java program to demonstrate the example 
// of BigInteger modPow(BigInteger exp, BigInteger val)
// method of BigInteger

import java.math.*;

public class ModPowOfBI {
    public static void main(String args[]) {
        // Initialize three variables str, exp and mod
        String str = "10";
        String exp = "2";
        String mod = "11";

        // Initialize three BigInteger objects  
        BigInteger b_int1 = new BigInteger(str);
        BigInteger b_int2 = new BigInteger(exp);
        BigInteger b_int3 = new BigInteger(mod);

        // Display b_int1 , b_int2 and b_int3
        System.out.println("b_int1: " + b_int1);
        System.out.println("b_int2: " + b_int2);
        System.out.println("b_int3: " + b_int3);

        // Here, we are calculating modPow between
        // two BigInteger values and it is calculated 
        // by using[(this BigInteger b_int1 pow (b_int2))
        // mod (BigInteger b_int3) ] like 10^2 mod 11
        BigInteger modpow_val = b_int1.modPow(b_int2, b_int3);
        System.out.println("b_int1.modPow(b_int2,b_int3): " + modpow_val);
    }
}

Output

b_int1: 10
b_int2: 2
b_int3: 11
b_int1.modPow(b_int2,b_int3): 1



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.