首页 > 代码库 > ACM常用模板

ACM常用模板

数论:

中国剩余定理(互质与非互质通用版)

技术分享
int m[3],r[3];
int e_gcd(int a,int b,int &x,int &y) {
    if(b==0) {
        x=1;
        y=0;
        return a;
    }
    int ans=e_gcd(b,a%b,x,y);
    int temp=x;
    x=y;
    y=temp-a/b*y;
    return ans;
}
int Zhong() {
    int M = m[0],R = r[0];
    for(int i = 1; i < 3; i++) {
        int c = r[i]-R,x,y;
        int gcd = e_gcd(M,m[i],x,y);
        if(c%gcd != 0) return -1;
        x = c*x;
        x = (x+m[i]) % m[i];
        int X = x*M + R;
        M = m[i]/gcd*M;
        R = X % M;
    }
    return (R%M+M)%M;
}
View Code

 

ACM常用模板