Last active
April 15, 2022 11:13
-
-
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)].
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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