主要是求解模不同的数同余的问题。
eg:《孙子算经》中有这样一个问题:“今有物不知其数,三三数之剩二(除以3余2),五五数之剩三(除以5余3),七七数之剩二(除以7余2),问物几何?”
板子
#include <iostream>
#include <cstdio>
#include<cstring>
#include<string>
using namespace std;
typedef long long LL;
const int maxn = 100000 + 10;
LL a[maxn],m[maxn],n;
LL ex_gcd(LL a,LL b,LL &x,LL &y){//拓展欧几里得
if(b==0){x = 1;y = 0;return a;}
LL ans = ex_gcd(b,a%b,x,y);
LL temp = x;
x = y;
y = temp - a/b*y;
return ans;
}
LL inv(LL a,LL b){//求逆元
LL x,y;
LL ans = ex_gcd(a,b,x,y);
if(ans!=1)return -1;
if(x<0)x = (x%b + b)%b;
return x;
}
LL China(){//中国剩余定理
LL M = 1;
for(int i = 0;i<n;i++){
M*=m[i];
}
LL sum = 0;
for(int i = 0;i<n;i++){
LL res = M/m[i];
sum = (sum + a[i]*res*inv(res,m[i]))%M;
}
return sum;
}
int main()
{
while(scanf("%lld",&n)!=EOF){
for(int i = 0;i<n;i++){
scanf("%lld%lld",&m[i],&a[i]);
}
LL ans = China();
printf("%lld\n",ans);
}
return 0;
}
来源:CSDN
作者:爱吃老谈酸菜的DV
链接:https://blog.csdn.net/weixin_43460224/article/details/103517212