-
Notifications
You must be signed in to change notification settings - Fork 0
/
FindingPower.java
36 lines (34 loc) · 964 Bytes
/
FindingPower.java
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
//time complexity is O(log n base 2)
//space complexity is O(n)
import java.util.*;
public class FindingPower {
public static long powerFind(int num, long pow)
{
long mid=0, result=0, finalResult=0;
if (pow == 0) {
return 1;
} else if(pow==1)
return num;
else
{
mid = pow/2;
result = powerFind(num, mid);
finalResult = result * result;
if(pow%2!=0)
{
finalResult = finalResult * num;
}
}
return finalResult;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int num = sc.nextInt();
System.out.println("Enter the power");
int pow = sc.nextInt();
long result = powerFind(num, pow);
System.out.println("The result is " + result);
sc.close();
}
}