Skip to content

Enhance code density and readability #4914

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

// 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.
Expand All @@ -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
Expand Down