Last active
March 28, 2019 19:58
-
-
Save Chillee/cfeef064991315737f8edba0837bf3f6 to your computer and use it in GitHub Desktop.
Binary Exponentiation
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
int binExp(int b, int pw) { | |
if (pw == 0) | |
return 1; | |
return binExp(b * b % MOD, pw / 2) * (pw & 1 ? b : 1) % MOD; | |
} |
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
const int bits = 10; | |
const int po = 1 << bits; | |
// if all numbers are less than 2ˆk , set bits = 64−k | |
ull modMul(ull a, ull b, ull &c) { | |
ull x = a * (b & (po - 1)) % c; | |
while ((b >>= bits) > 0) { | |
a = (a << bits) % c; | |
x += (a * (b & (po - 1))) % c; | |
} | |
return x % c; | |
} | |
ull binExp(ull b, ull pw, ull MOD) { | |
if (pw == 0) | |
return 1; | |
return modMul(binExp(modMul(b, b, MOD), pw / 2, MOD), (pw & 1 ? b : 1), MOD); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
BinExp64 runs in O(64/bits * log b)