| 1. |
Write a Java Program to calculate xn (x to the power n) using Recursion. You can use O(N) time but can’t use any extra space apart from the Recursion Call Stack Space. |
|
Answer» In a recursive function, we need to find a relation between the smaller problem and the larger problem. Here, we have a clear mathematical relationship between the large problem xn and the problem that is smaller than it i.e. x to the power (n-1). The relation is: xn = x * xn-1{"detectHand":false}The relation is: (x to the power n) = x * x to the power(n-1) In terms of programming (using functions), we can write this relation as: power(x,n) = x * power(x,n-1) For example, 2 to the power 5 = 32. This can be calculated as 2 * (2 to the power 4) = 2 * 16 = 32. So, we have found the recurrence relation in the above equation. Now, what will be the base case? The base case will be the smallest such problem that we can solve. So, the smallest problem is calculating the power of 0 to any number. We know that any number to the power 0 gives the result as 1. So, this will be our base case. Now, let us write the code for the same. Java Code to Calculate x to the power n import java.util.*;class Main { public static double power(double x, int n) { if(n == 0) return 1.0; double xpnm1 = power(x,n-1); //x power n-1 (xpnm1) return x * xpnm1; } public static double pow(double x, int n) { if(n < 0) { return 1.0 / power(x,-n); } return power(x,n); } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); double x = scn.nextDouble(); int n = scn.nextInt(); System.out.println(pow(x,n)); } } Sample Output:
1.10 3 Output: 1.3676310000000003
1.110 -3 Output: 0.7311913813009502
|
|