how to evaluate Modular Exponentiation in Java

Hi, today we will learn how to evaluate Modular Exponentiation in Java. This tutorial will help you to learn about some built-in methods that we will use here.

First of all, do you know what is Modular Exponentiation?

Modular exponentiation is a type of exponentiation performed over a modulus. It is useful in Computer Science in the field of public-key cryptography.

So, how to evaluate Modular Exponentiation. Suppose, we have three variables base x, exponent y, and modulus m. Modular Exponentiation z  for these numbers will be calculated based on the given formula:

z = (xˆy) % m

where, will be an integer lie in the interval [0, m).

Now, the problem is how to implement it using the software. The problem arises due to the limited holding capacity of our variables which can hamper the actual result.

For this problem, Java offers some built-in methods to perform these tasks. These lie in java.math.BigInteger package where BigInteger is the name of the class.

Syntax of the function we will use in this tutorial is:

public BigInteger modpow(BigInteger exponent,BigInteger m)

The above method returns a BigInteger object whose value will be (thisˆexponent) % m.

Please Remember there could be multiple ways to solve a particular problem as per your understanding. let’s see how to evaluate Modular Exponentiation using java.

Evaluate Modular Exponentiation: Java code

import java.math.BigInteger;
 
public class Main {
    public static void main(String[] args){
        BigInteger x = new BigInteger("2"),y = new BigInteger("5"),m = new BigInteger("31");
        System.out.println(x.modPow(y,m));
    }
}

Output:

1

Explanation:

So, first it calculate: 2 x 2 x 2 x 2 x 2 = 32 ,and then, 32%31 = 1 which it displays on screen. Also, If you want to check your custom inputs then you can take them in a String variable and then pass them in the constructor at the time of the creation of objects of class BigInteger.

Now, you know how to compute or evaluate Modular exponentiation in java in a few seconds.

You may also read:

How to check if the given date is valid or not in Java

How to reverse a LinkedList in Java

 

Leave a Reply

Your email address will not be published. Required fields are marked *