参考:https://www.cnblogs.com/MashiroSky/p/5918158.html
问题
求x?
m[]互质
推理过程详见上面链接
poj1006互质版裸题
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int a[4],m[4],d;
void extend_Euclid(int a,int b,int &x,int &y){
if(b == 0){
x = 1;
y = 0;
return ;
}
extend_Euclid(b,a % b,x,y);
int tmp = x;
x = y;
y = tmp - (a / b) * y;
}
int CRT(int a[],int m[],int n){
int M = 1;
int ans = 0;
for(int i = 1;i <= n; i++) M *= m[i];
for(int i = 1;i <= n; i++){
int x,y;
int Mi = M / m[i];
extend_Euclid(Mi,m[i],x,y);//x是Mi%mi的逆元
ans = (ans + Mi * x * a[i]) % M;
}
if(ans < 0) ans += M;
return ans;
}
int main()
{
int cnt = 0;
while(~scanf("%d %d %d %d",&a[1],&a[2],&a[3],&d)){
cnt ++;
if(a[1] == -1 && a[2] == -1 && a[3] == -1) break;
m[1] = 23;
m[2] = 28;
m[3] = 33;
int ans = CRT(a,m,3);
if(ans <= d) ans += 23 * 28 * 33;
ans -= d;
printf("Case %d: the next triple peak occurs in %d days. \n",cnt,ans);
}
return 0;
}
hdu3579不互质
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int MaxN = 1e3 + 5;
int m[MaxN],a[MaxN],t,n,cas;
int extend_Euclid(int a,int b,int &x,int &y){
int d;
if(b == 0){
x = 1;
y = 0;
return a;
}
d = extend_Euclid(b,a % b,y,x);
y -= a / b * x;
return d;
}
int CRT(int a[],int m[],int len){
bool flag = false;
int n1 = m[0],b1 = a[0],x,y;
for(int i = 1;i < len; i++){
int n2 = m[i],b2 = a[i];
int bb = b2 - b1;
int d = extend_Euclid(n1,n2,x,y);
if(bb % d){
flag = true;
break;
}
int k = bb / d * x;
int t = n2 / d;
if(t < 0) t = -t;
k = (k % t + t) % t;
b1 = b1 + n1 * k;
n1 = n1 / d * n2;
}
if(flag) return -1;
return b1;
}
int main()
{
cas = 1;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(int i = 0; i < n; i++) scanf("%d",&m[i]);
for(int i = 0; i < n; i++) scanf("%d",&a[i]);
if(n == 1 && a[0] == 0){
printf("Case %d: %d\n",cas++,m[0]);
continue;
}
printf("Case %d: %d\n",cas++,CRT(a,m,n));
}
return 0;
}