w3resource

Java: Compute xn % y where x, y and n are all 32bit integers


Compute Modular Exponentiation

Write a Java program to compute xn % y where x, y and n are all 32-bit integers.

Sample Solution:

Java Code:

// Import Scanner class from java.util package for user input
import java.util.*;

// Main class for the solution
public class Main {
    // Main method to execute the solution
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner in = new Scanner(System.in);

        // Prompt the user to input x
        System.out.print("Input x : ");
        // Read the user input as an integer
        int x = in.nextInt();

        // Prompt the user to input n
        System.out.print("Input n : ");
        // Read the user input as an integer
        int n = in.nextInt();

        // Prompt the user to input y
        System.out.print("Input y : ");
        // Read the user input as an integer
        int y = in.nextInt();

        // Calculate the result of x raised to the power of n
        double result = Math.pow(x, n);

        // Calculate the remainder when result is divided by y
        double result1 = result % y;

        // Display the result of (x^n % y)
        System.out.println("x^n % y = " + result1);
    }
} 

Sample Output:

Input x :  25
Input n :  35
Input y :  45
x^n % y = 5.0

Flowchart:

Flowchart: Java exercises: Compute  x<sup>n</sup> % y where x, y and n are all 32bit integers.


For more Practice: Solve these Related Problems:

  • Write a Java program to compute modular exponentiation using iterative squaring without built-in libraries.
  • Write a Java program to compute (x^n) % y for negative exponents by applying modular multiplicative inverses.
  • Write a Java program to compute modular exponentiation with very large n using recursion with memoization.
  • Write a Java program to compare recursive and iterative approaches for computing (x^n) % y and analyze their performance.

Go to:


PREV : Max Average of Subarray.
NEXT : Check If Power of Two in O(1).

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.