w3resource

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

Java Basic: Exercise-204 with Solution

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.

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.



Follow us on Facebook and Twitter for latest update.