Java Program to find x to the power y (xy).
Objective
Write a Java program to find the value of a number raised to the power of another.
Algorithm / Approach
- Prompt the user to enter a base and an exponent.
- Use
Math.pow(x, y)to calculate the power. - Cast the resulting
doubleinto anintif a whole number is desired. - Print the result.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Base: ");
int x = s.nextInt();
System.out.print("Enter Power: ");
int y = s.nextInt();
int r =(int) Math.pow(x,y);
System.out.println("Result = "+r);
}
}
Expected Output
Enter Base: 5 Enter Power: 3 Result = 125
Explanation of the Program
- The base
xand exponentyare taken as input. - The
Math.pow(x, y)method computesxraised to the power ofy. - Because
Math.pow()returns adouble, it is explicitly cast to anintbefore being stored inr.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Forgetting to cast
Math.pow()to anintwhen integer output is needed. - Swapping the base and the exponent arguments.