BigInteger modPow() Method in Java

Prerequisite: BigInteger Basics

The Java.math.BigInteger.modPow() method returns a BigInteger whose value is (thisexponent mod m ).

If exponent == 1, the returned value is (this mod m) and if exponent < 0, the returned value is the modular multiplicative inverse of (this-exponent). The method throws an ArithmeticException if m <= 0.

Syntax:

public BigInteger modPow(BigInteger exponent, BigInteger m)

Parameters: The method accepts two parameters.



  • exponent: This parameter refers to the exponent.
  • m: This parameter refers to the modulus.

Return Value: The method returns a BigInteger object whose value is ( thisexponent mod m ).

Exceptions:

  • ArithmeticException: If (m <= 0) or the exponent is negative and this BigInteger is not relatively prime to m.

Examples:

Input: biginteger1 = 23895 
                        exponent = 15
                        biginteger2 = 14189
Output: 344
Explanation:
result = biginteger1.modPow(exponent, biginteger2)
23895^15 % 14189 = 344

Input: biginteger1 = 6547890621
       exponent = 4532415
       biginteger2 = 76543278906
Output: 1039609179
Explanation:
6547890621^4532415 % 76543278906 = 1039609179

Below program illustrates the Java.math.BigInteger.modPow() method:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Code to illustrate modpow() method of BigInteger 
import java.math.*;
import java.util.Scanner;
  
public class GFG {
  
    public static void main(String[] args)
    {
  
        // Create 3 BigInteger objects
        BigInteger biginteger1, biginteger2, result;
  
        // Intializing all BigInteger Objects
        biginteger1 = new BigInteger("23895");
        biginteger2 = new BigInteger("14189");
        BigInteger exponent = new BigInteger("15");
  
        // Perform modPow operation on the objects and exponent
        result = biginteger1.modPow(exponent, biginteger2);
        String expression = biginteger1 + "^" + exponent + " % "
                            + biginteger2 + " = " + result;
  
        // Displaying the result
        System.out.println(expression);
    }
}

chevron_right


Output:

23895^15 % 14189 = 344

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#abs()

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.