模板逆元
Posted dukelv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板逆元相关的知识,希望对你有一定的参考价值。
很基础的东西,但是不能马虎,有3种方法,下面一一列举。
一.线性求逆元
#include<iostream> #include<cstdio> #include<cmath> #include<ctime> #include<queue> #include<algorithm> #include<cstring> using namespace std; #define duke(i,a,n) for(int i = a;i <= n;i++) #define lv(i,a,n) for(int i = a;i >= n;i--) #define clean(a) memset(a,0,sizeof(a)) const int INF = 1 << 30; typedef long long ll; typedef double db; template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < ‘0‘ || c > ‘9‘) if(c == ‘-‘) op = 1; x = c - ‘0‘; while(c = getchar(), c >= ‘0‘ && c <= ‘9‘) x = x * 10 + c - ‘0‘; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) putchar(‘-‘), x = -x; if(x >= 10) write(x / 10); putchar(‘0‘ + x % 10); } int n; ll p,inv[3000005]; void work() { inv[1] = 1; duke(i,2,n) { inv[i] = (p - p / i) * inv[p % i] % p; } duke(i,1,n) { printf("%lld ",inv[i]); } } int main() { read(n);read(p); work(); return 0; }
二.费马小定理求逆元
#include<iostream> #include<cstdio> #include<cmath> #include<ctime> #include<queue> #include<algorithm> #include<cstring> using namespace std; #define duke(i,a,n) for(int i = a;i <= n;i++) #define lv(i,a,n) for(int i = a;i >= n;i--) #define clean(a) memset(a,0,sizeof(a)) const int INF = 1 << 30; typedef long long ll; typedef double db; template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < ‘0‘ || c > ‘9‘) if(c == ‘-‘) op = 1; x = c - ‘0‘; while(c = getchar(), c >= ‘0‘ && c <= ‘9‘) x = x * 10 + c - ‘0‘; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) putchar(‘-‘), x = -x; if(x >= 10) write(x / 10); putchar(‘0‘ + x % 10); } ll n,p; ll qpow(ll x,ll y) { ll tot = 1; while(y) { if((y & 1) != 0) { tot *= x; } x *= x; x %= p; tot %= p; y >>= 1; } return tot; } int main() { read(n);read(p); printf("%lld ",qpow(n,p - 2)); return 0; }
三.exgcd求逆元
#include<iostream> #include<cstdio> #include<cmath> #include<ctime> #include<queue> #include<algorithm> #include<cstring> using namespace std; #define duke(i,a,n) for(int i = a;i <= n;i++) #define lv(i,a,n) for(int i = a;i >= n;i--) #define clean(a) memset(a,0,sizeof(a)) const int INF = 1 << 30; typedef long long ll; typedef double db; template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < ‘0‘ || c > ‘9‘) if(c == ‘-‘) op = 1; x = c - ‘0‘; while(c = getchar(), c >= ‘0‘ && c <= ‘9‘) x = x * 10 + c - ‘0‘; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) putchar(‘-‘), x = -x; if(x >= 10) write(x / 10); putchar(‘0‘ + x % 10); } ll exgcd(ll a,ll b,ll &x,ll &y) { if(a == 1 && b == 0) { x = 1; y = 0; return 1; } ll t = exgcd(b,a % b,y,x); y -= a / b * x; return t; } int main() { ll n,p,x,y; read(n);read(p); ll t = exgcd(n,p,x,y); printf("%lld ",(x % p + p) % p); return 0; }
以上是关于模板逆元的主要内容,如果未能解决你的问题,请参考以下文章