forked from Rishabh062/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryExponentiation.java
More file actions
32 lines (29 loc) · 908 Bytes
/
BinaryExponentiation.java
File metadata and controls
32 lines (29 loc) · 908 Bytes
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
package com.saikat;
import java.util.Scanner;
public class BinaryExponentiation {
public static void main(String[] args) {
System.out.println("Enter base number");
Scanner in = new Scanner(System.in);
double base = in.nextDouble();
System.out.println("Enter exponent");
int power = in.nextInt();
System.out.println(binaryExponentiation(base, power));
}
static double binaryExponentiation(double x, int n)
{
if(n<0)
return negPow(x,n);
if(n==0)
return 1; //base case
double res = binaryExponentiation(x,n/2);
if(n%2==1)
return x*(res*res); // if n is odd
return res*res;
}
static double negPow(double x, int n)
{
if(n<0)
return 1/x*negPow(1/x,-(n+1));
return binaryExponentiation(x,n);
}
}