標籤:double const main typedef mem def printf 馬虎 不能
很基礎的東西,但是不能馬虎,有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\n",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\n",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\n",(x % p + p) % p); return 0;}
【模板】逆元