This is the Java Program to Implement the pow() Function.
Given a value say x, and an exponent n, write a program to calculate x raised to the power n.
The value x raised to the power n can be calculated, using a simple recursive algorithm. If the exponent is 1 return the variable x. Otherwise, recursively call the function on half of the exponent. If the exponent is even, multiply the result obtained from the recursive call by itself and in case if the exponent is odd also multiply x after multiplying the result.
Here is the source code of the Java Program to Implement the pow() Function. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
// Java Program to Implement the pow() Function
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Power {
// Function to calculate power of x raised to n
static double pow(double x, int n){
if(n<0){
return pow(1/x,-n);
}
if(n==1)
return x;
else if(n%2 == 0){
double y = pow(x,n/2);
return y*y;
}
double y = pow(x,n/2);
return y*y*x;
}
// Function to read user input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double x;
int n;
try {
System.out.println("Enter the number");
x = Double.parseDouble(br.readLine());
System.out.println("Enter the exponent (in integer)");
n = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error occurred");
return;
}
double result = pow(x,n);
System.out.printf(x + " raised to " + n + " is %f", result);
}
}
1. In function pow(), firstly the exponent is checked. If it is negative, then the recursive call is made on the reciprocal of x, with negative of the exponent.
2. If the exponent is 1, then simply x is returned.
3. If the exponent is even, then a recursive call with half of the exponent is made and finally the result is squared.
4. If the exponent is odd, then a recursive call with half of the exponent is made and finally the result is squared and multiplied with x.
Time Complexity: O(log(n)) where n is the exponent.
Case 1 (Simple Test Case): Enter the number 3.5 Enter the exponent (in integer) 5 3.5 raised to 5 is 525.218750 Case 2 (Simple Test Case - another example): Enter the number 2 Enter the exponent (in integer) -2 2.0 raised to -2 is 0.250000
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Practice Programming MCQs
- Practice BCA MCQs
- Apply for Computer Science Internship
- Practice Information Technology MCQs