【hdu3579-Hello Kiki】拓展欧几里得-同余方程组
http://acm.hdu.edu.cn/showproblem.php?pid=3579
题解:同余方程组的裸题。注意输出是最小的正整数,不包括0。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> using namespace std; typedef long long LL; const int N=20; LL exgcd(LL a,LL b,LL &x,LL &y) { if(b==0) {x=1,y=0; return a;} LL tx,ty; LL d=exgcd(b,a%b,tx,ty); x=ty; y=tx-(a/b)*ty; return d; } int main() { // freopen("a.in","r",stdin); // freopen("a.out","w",stdout); int n,T; scanf("%d",&T); LL a[N],b[N]; for(int TT=1;TT<=T;TT++) { scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%I64d",&a[i]); for(int i=1;i<=n;i++) scanf("%I64d",&b[i]); LL a1=a[1],b1=b[1]; bool bk=1; for(int i=2;i<=n;i++) { LL A=a1,B=a[i],C=b[i]-b1,x,y; LL g=exgcd(A,B,x,y); if(C%g) {bk=0;break;} x=((x*C/g)%(B/g)+(B/g))%(B/g); b1=a1*x+b1; a1=a1/g*a[i]; } if(!bk) printf("Case %d: -1\n",TT); else{ /* a1x+b1=P;(a1>=0,P求的是最小正整数) b1!=0 --> x=0,b1=P b1==0 --> x=1,a1=P */ if(b1) printf("Case %d: %I64d\n",TT,b1); else printf("Case %d: %I64d\n",TT,a1); } } return 0; }