Add more tests (#3601)

This commit is contained in:
Debasish Biswas
2022-10-25 17:45:41 +05:30
committed by GitHub
parent 6235fd6505
commit 315e947c87
4 changed files with 125 additions and 66 deletions

View File

@ -1,22 +1,39 @@
package com.thealgorithms.divideandconquer;
// Java Program to Implement Binary Exponentiation (power in log n)
/*
* Binary Exponentiation is a method to calculate a to the power of b.
* It is used to calculate a^n in O(log n) time.
*
* Reference:
* https://iq.opengenus.org/binary-exponentiation/
*/
public class BinaryExponentiation {
public static void main(String args[]) {
System.out.println(calculatePower(2, 30));
}
// Function to calculate x^y
// Time Complexity: O(logn)
// recursive function to calculate a to the power of b
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;
if (y % 2 == 0) {
return val * val;
}
return val;
return val * val * x;
}
// iterative function to calculate a to the power of b
long power(long N, long M) {
long power = N, sum = 1;
while (M > 0) {
if ((M & 1) == 1) {
sum *= power;
}
power = power * power;
M = M >> 1;
}
return sum;
}
}