Java: Compute xn % y where x, y and n are all 32bit integers
Java Basic: Exercise-204 with Solution
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:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to find the contiguous subarray of given length k which has the maximum average value of a given array of integers. Display the maximum average value.
Next: Write a Java program to check whether an given integer is power of 2 or not using O(1) time.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/basic/java-basic-exercise-204.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics