mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-14 17:32:35 +08:00
Add Binary Exponentiation (#2359)
This commit is contained in:
16
DivideAndConquer/BinaryExponentiation.java
Normal file
16
DivideAndConquer/BinaryExponentiation.java
Normal file
@ -0,0 +1,16 @@
|
||||
public class BinaryExponentiation {
|
||||
|
||||
public static void main(String args[]) {
|
||||
System.out.println(calculatePower(2, 30));
|
||||
}
|
||||
|
||||
// Function to calculate x^y
|
||||
// Time Complexity: O(logn)
|
||||
public static long calculatePower(long x, long y) {
|
||||
if (y == 0) return 1;
|
||||
long val = calculatePower(x, y / 2);
|
||||
val *= val;
|
||||
if (y % 2 == 1) val *= x;
|
||||
return val;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user