diff options
Diffstat (limited to 'math/modExp.cpp')
| -rw-r--r-- | math/modExp.cpp | 24 |
1 files changed, 17 insertions, 7 deletions
diff --git a/math/modExp.cpp b/math/modExp.cpp index f738268..863ff4e 100644 --- a/math/modExp.cpp +++ b/math/modExp.cpp @@ -1,7 +1,17 @@ -ll modPow(ll b, ll e, ll p) { - if (e == 0) return 1; - if (e == 1) return b; - ll half = modPow(b, e / 2, p), res = (half * half) % p; - if (e & 1) res *= b; res %= p; - return res; -}
\ No newline at end of file +//0<=a,b <=n and n <= MAX(ll)/2 +ll mult_mod(ll a, ll b, ll n) { + if(a == 0 || b == 0) return 0; + if(b == 1) return a % n; + + if(b % 2 == 1) return (a + mult_mod(a, b-1, n)) % n; + else return mult_mod((a + a) % n, b / 2, n); +} + +//0<=a,b<=n and n <= MAX(ll)/2 +ll pow_mod(ll a, ll b, ll n) { + if(b == 0) return 1; + if(b == 1) return a % n; + + if(b % 2 == 1) return mult_mod(pow_mod(a, b-1, n), a, n); + else return pow_mod(mult_mod(a, a, n), b / 2, n); +} |
