Home >Backend Development >C++ >How to Efficiently Calculate (a^b)%MOD with Large Exponents?
Calculating (a^b)%MOD with Large Exponents
In this coding challenge, the task is to calculate the value of pow(a, b)%MOD, where the exponent b can be extremely large. While the conventional log(b) time complexity method is suitable for smaller values, it becomes impractical when b exceeds the capacity of long long data types in C .
However, a more efficient approach involves leveraging Euler's totient function, φ(MOD). Euler's theorem states that a^φ(MOD)≡1(mod MOD). This means that the power of a can be significantly reduced to a^(b % φ(MOD)).
Calculating φ(MOD) is itself a non-trivial task, but can be achieved using integer factorization methods. Once calculated, the exponent b can be replaced with b % φ(MOD) to dramatically reduce the computation time.
Further Refinements
In 2008, Schramm demonstrated that φ(b) can be obtained from the discrete Fourier transform of gcd(b, i), for i ranging from 1 to b. This eliminates the need for explicit factorization.
Additionally, Carmichael's function, λ(MOD), can be used to obtain the correct answer, especially when a and MOD share common factors.
Code Implementation
The following code snippet serves as an example in C :
<code class="cpp">#include <iostream> #include <vector> using namespace std; typedef long long ll; ll gcd(ll a, ll b) { return (b == 0) ? a : gcd(b, a % b); } ll pmod(ll a, ll b, ll mod) { if (b == 0) return 1; if (b % 2 == 1) { return (a * pmod(a, b - 1, mod)) % mod; } else { ll tmp = pmod(a, b / 2, mod); return (tmp * tmp) % mod; } } int main() { ll a, b, mod; cin >> a >> b >> mod; cout << pmod(a, b % phi(mod), mod) << endl; return 0; }</code>
The above is the detailed content of How to Efficiently Calculate (a^b)%MOD with Large Exponents?. For more information, please follow other related articles on the PHP Chinese website!