于是便可以按这种方法,求出上面的 n 个方程组的解,然后便得到了原方程的整数解。不过还要再进行对所有的数的乘积的取模,因为要求最小非负整数解。
所以,设所有的数的乘积为 k,则最终答案用式子表达便是:
x=i=1∑nki×ai×mi(modk)
代码
开了 __int128。
C++
#include<bits/stdc++.h>#define int __int128
using namespace std;
const int MAXN = 1e5 + 10;
int n;
int a[MAXN] , b[MAXN];
int s;
int exgcd(int a , int b , int &x , int &y) {
if(!b) {
x = 1;
y = 0;
return a;
}
int r = exgcd(b , a % b , x , y);
int t = x;
x = y;
y = t - a / b * y;
return r;
}
inline int read() {
char c = getchar();
int x = 0 , s = 1;
while(c < '0' || c > '9') {
if(c == '-')
s = -1;
c = getchar();
}
while(c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = getchar();
}
return x * s;
}
void write(int x){
if(x > 9)
write(x/10);
putchar(x % 10 | 48);
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
n = read();
int ans = 1;
for(register int i = 1;i <= n;i ++) {
a[i] = read();
b[i] = read();
ans *= a[i];
}
for(register int i = 1;i <= n;i ++) {
int k = ans / a[i];
int x , y;
exgcd(k , a[i] , x , y);
s = s + k * b[i] * x % ans;
}
write((s % ans + ans) % ans);
return 0;
}