Skip to content

Commit 7a1c4b0

Browse files
Add Binary Exponentiation (TheAlgorithms#2359)
1 parent 3602904 commit 7a1c4b0

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
public class BinaryExponentiation {
2+
3+
public static void main(String args[]) {
4+
System.out.println(calculatePower(2, 30));
5+
}
6+
7+
// Function to calculate x^y
8+
// Time Complexity: O(logn)
9+
public static long calculatePower(long x, long y) {
10+
if (y == 0) return 1;
11+
long val = calculatePower(x, y / 2);
12+
val *= val;
13+
if (y % 2 == 1) val *= x;
14+
return val;
15+
}
16+
}

0 commit comments

Comments
 (0)