按照m之间的性质来决定采用什么方法
-
是否互质?
-
互质——中国剩余定理
-
不互质——拓展欧几里得 + 拓展中国剩余定理
-
-
互质情况下,是否均为质数?
-
是—— 费马小定理求逆元
-
否——拓展欧几里得求逆元
-
互质条件下的拓展欧几里得+中国剩余定理
题目(本题mi会爆long long,要么高精度、要么__int128,要么用拓展欧几里得)
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef __int128 bt;
const int N = 11;
ll m[N], r[N];
int n;
ll ex_gcd(ll a, ll b, ll& x, ll& y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll gcd = ex_gcd(b, a%b, x, y);
ll tmp = x;
x = y;
y = tmp - a / b * y;
return gcd;
}
ll crt(ll m[], ll r[])
{
ll res = 0;
bt mi = 1;
for(int i = 1; i <= n; i++)
mi *= m[i];
ll x, y, M;
for(int i = 1; i <= n; i++)
{
M = mi / m[i];
ll gcd = ex_gcd(M, m[i], x, y);
if(r[i] % gcd) return -1;
x /= gcd;
x = (x % (m[i] / gcd) + (m[i] / gcd)) % (m[i] / gcd);
res = (res + r[i] * M % mi * x % mi) % mi;
}
return res;
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
cin >> m[i] >> r[i];
ll res = crt(m, r);
cout << res;
}
无互质条件下的拓展欧几里得+拓展中国剩余定理
题目
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 26;
ll m[N], r[N];
int n;
ll ex_gcd(ll a, ll b, ll&x, ll& y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll gcd = ex_gcd(b, a % b, x, y);
ll tmp = x;
x = y;
y = tmp - a / b * y;
return gcd;
}
ll ex_crt(ll m[], ll r[])
{
ll m1, m2, r1, r2, x, y;
m1 = m[1], r1 = r[1];
for(int i = 2; i <= n; i++)
{
m2 = m[i], r2 = r[i];
ll gcd = ex_gcd(m1, m2, x, y);
if((r2-r1) % gcd) return -1;
x = x * (r2-r1) / gcd;
x = (x % (m2 / gcd) + (m2 / gcd)) % (m2 / gcd);
r1 = m1 * x + r1;
m1 = m1 * m2 / gcd;
}
return (r1 % m1 + m1) % m1;
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
cin >> m[i] >> r[i];
cout << ex_crt(m, r);
}