備戰NOIP——模板複習24
阿新 • • 發佈:2018-12-20
這裡只有模板,並不作講解,僅為路過的各位做一個參考以及用做自己複習的資料,轉載註明出處。
逆元
費馬小定理
/*Copyright: Copyright (c) 2018 *Created on 2018-11-07 *Author: 十甫 *Version 1.0 *Title: 逆元-費馬小定理 *Time: 2 mins */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef long long ll; inline ll mul(ll a, ll b, ll mod) { ll res = 1; while(b) { if(b & 1) res = ((res % mod) * (a % mod)); a = ((a % mod) * (a % mod)); b /= 2; } return res; } int main() { ll n, k; scanf("%lld%lld", &n, &k); printf("%lld\n", mul(n, k - 2, k)); return 0; }
EX-GCD
/*Copyright: Copyright (c) 2018 *Created on 2018-11-07 *Author: 十甫 *Version 1.0 *Title: 逆元-EX-GCD *Time: 2 mins */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef long long ll; inline void exgcd(ll a, ll b, ll &x, ll &y, ll mod) { if(!b) { x = 1, y = 0; return; } exgcd(b, a % b, y, x, mod); y -= (a / b) * x; y = (y + mod) % mod; } int main() { ll n, k; scanf("%lld%lld", &n, &k); ll a, b; exgcd(n, k, a, b, k); printf("%lld\n", a); return 0; }
線性遞推
/*Copyright: Copyright (c) 2018 *Created on 2018-11-07 *Author: 十甫 *Version 1.0 *Title: 逆元-線性遞推 *Time: inf mins */ #include<iostream> #include<cstring> #include<cstdio> using namespace std; const int size = 10005; int inv[size]; inline void make(int n, int p) { inv[1] = 1; for(int i = 2;i <= n;i++) { inv[i] = inv[p % i] * (p - p / i) % p; } } int main() { int n, p; scanf("%d%d", &n, &p); make(n, p); printf("%d\n", inv[n]); return 0; }