中国剩余定理(Gym - 102091H)
中国剩余定理又名孙子定理。其本质是求解同余方程组。前置知识:同余式,扩展欧几里得
删除线格式
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
ll prime[4], r[4];
ll exgcd(ll a, ll b, ll &x, ll &y)//扩展欧几里得
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll d = exgcd(b, a % b, x, y), temp = x;
x = y;
y = temp - a / b * y;
return d;
}
ll CRT()//孙子定理
{
ll ans = r[1], M = prime[1];
for(int i = 2; i <= 3; i ++)
{
ll aa = M, bb = prime[i], cc = (r[i] - ans % bb + bb) % bb;
ll x, y;
ll d = exgcd(aa, bb, x, y);
if(cc % d)//同余式无解
return -1;
bb /= d;
cc /= d;
x = (x * cc % bb + bb) % bb;
ans += x * M;
M *= bb;
ans = (ans % M + M) % M;
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
int t;
cin >> t;
while(t --)
{
for(int i = 1; i <= 3; i ++)
cin >> prime[i];
for(int i = 1; i <= 3; i ++)
cin >> r[i];
ll d = CRT();
if(d == -1)
{
cout << -1 << endl;
}
else
{
ll temp = pow(d, 1.0 / 3.0);
if(temp * temp * temp < d)
cout << temp + 1 << endl;
else
cout << temp << endl;
}
}
}