Enhance code density and readability (#4914)
* Enhance code density and readability * Add wiki link --------- Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
This commit is contained in:
parent
e5f3d232c9
commit
d086afce09
@ -2,6 +2,8 @@ package com.thealgorithms.divideandconquer;
|
||||
|
||||
// Java Program to Implement Binary Exponentiation (power in log n)
|
||||
|
||||
// Reference Link: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
|
||||
|
||||
/*
|
||||
* 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.
|
||||
@ -14,14 +16,14 @@ public class BinaryExponentiation {
|
||||
|
||||
// recursive function to calculate a to the power of b
|
||||
public static long calculatePower(long x, long y) {
|
||||
// Base Case
|
||||
if (y == 0) {
|
||||
return 1;
|
||||
}
|
||||
long val = calculatePower(x, y / 2);
|
||||
if (y % 2 == 0) {
|
||||
return val * val;
|
||||
if (y % 2 == 1) { // odd power
|
||||
return x * calculatePower(x, y - 1);
|
||||
}
|
||||
return val * val * x;
|
||||
return calculatePower(x * x, y / 2); // even power
|
||||
}
|
||||
|
||||
// iterative function to calculate a to the power of b
|
||||
|
Loading…
Reference in New Issue
Block a user