forked from avinashbest/java-coding-ninjas
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculatePower.java
More file actions
48 lines (44 loc) · 1.04 KB
/
CalculatePower.java
File metadata and controls
48 lines (44 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package recursion1;
import java.util.Scanner;
/*Write a program to find x to the power n (i.e. x^n). Take x and n from the user. You need to return the answer.
Do this recursively.
Input format :
Two integers x and n (separated by space)
Output Format :
x^n (i.e. x raise to the power n)
Constraints :
1 <= x <= 30
0 <= n <= 30
Sample Input 1 :
3 4
Sample Output 1 :
81
Sample Input 2 :
2 5
Sample Output 2 :
32*/
public class CalculatePower {
public static int power(int x, int n) {
if (x == 0 && n == 0) {
return 1;
}
if (x == 0) {
return 0;
}
if (n == 0) {
return 1;
}
int smallAnswer = power(x, n / 2);
if (n % 2 == 0) {
return smallAnswer * smallAnswer;
} else {
return x * smallAnswer * smallAnswer;
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int n = scan.nextInt();
System.out.println(power(x, n));
}
}