Modular Exponentiation (Power in Modular Arithmetic) in java

Java Programming Java8Java.Math

The java.math.BigInteger.modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (this<sup>exponent</sup> mod m). Unlike pow, this method permits negative exponents. You can calculate the modular Exponentiation using this method.


Live Demo

import java.math.*;

public class BigIntegerDemo {
   public static void main(String[] args) {
      // create 3 BigInteger objects
      BigInteger bi1, bi2, bi3;
      // create a BigInteger exponent
      BigInteger exponent = new BigInteger("2");
      bi1 = new BigInteger("7");
      bi2 = new BigInteger("20");
      // perform modPow operation on bi1 using bi2 and exp
      bi3 = bi1.modPow(exponent, bi2);
      String str = bi1 + "^" +exponent+ " mod " + bi2 + " is " +bi3;
      // print bi3 value
      System.out.println( str );


7^2 mod 20 is 9
Updated on 25-Jun-2020 12:34:08