Skip to content

Instantly share code, notes, and snippets.

@Ch-sriram
Last active April 15, 2022 11:13
Show Gist options
  • Save Ch-sriram/0678934cc6bd8747f95d5e32ba50b4cf to your computer and use it in GitHub Desktop.
Save Ch-sriram/0678934cc6bd8747f95d5e32ba50b4cf to your computer and use it in GitHub Desktop.
Given Number a & N, compute a^N. [Optimal Solution: O(log N)].
// a^N using fast exponentiation
const int64_t M = (int64_t) 1e9+7; // very big prime number
int64_t pow_fast (int64_t a, int64_t N) {
int64_t ans = 1, x = a;
while (N != 0) {
if (N & 1)
ans = ((ans % M) * x) % M;
x = ((x % M) * x) % M;
N >>= 1;
}
return ans % M;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment