Skip to content

Instantly share code, notes, and snippets.

@NamPE286
Last active July 1, 2023 13:23
Show Gist options
  • Save NamPE286/74798bc82b45cf414ba2a352d849e198 to your computer and use it in GitHub Desktop.
Save NamPE286/74798bc82b45cf414ba2a352d849e198 to your computer and use it in GitHub Desktop.
Inverse modulo in C++ (a^-1 % m (m is prime)) (fermat's little theorem)
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
ll powMod(ll a, ll b, ll m) {
ll res = 1;
while (b) {
if (b % 2) res = (res * a) % m;
a = (a * a) % m;
b /= 2;
}
return res;
}
ll invMod(ll x, ll m) { // x^-1 % m (m is prime)
return powMod(x, m - 2, m);
}
int main() {
ll MOD = 998244353;
cout << (2 * invMod(3, MOD)) % MOD; // 665496236
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment