poj 2891 Strange Way to Express Integers 不互质的模同余方程组求解

给定同余方程组

  X = r1 ( mod  a1 )

  X = r2 ( mod a2 )

    ...

  X = rn ( mod an )

求解正整数X, 若不存在输出 -1

 

关于 线性同余方程组求解, 看笔者前一篇博客关于求解方式,模板裸题

#include<stdio.h>
typedef long long LL;
LL ExGcd( LL a, LL b, LL &x, LL &y )
{
    if( b == 0 ) { x=1;y=0; return a; }
    LL r = ExGcd( b, a%b, x, y );
    LL t = x; x = y; y = t - a/b*y;
    return r;
}
LL Modline( LL r[], LL a[], int n )
{
    //  X = r[i] ( mod a[i] ) 
    LL rr = r[0], aa = a[0];
    for(int i = 1; i < n; i++ )
    {
        // aa*x + a[i]*y = ( r[i] - rr );
        LL C = r[i] - rr, x, y;
        LL d = ExGcd( aa, a[i], x, y );
        if( (C%d) != 0 ) return -1;
        LL Mod = a[i]/d;    
        x = ( ( x*(C/d)% Mod ) + Mod ) % Mod;
        rr = rr + aa*x; // 余数累加
        aa = aa*a[i]/d; // n = n1*n2*...*nk
     }
    return rr;
}

int main()
{
    int n;
    LL r[10], a[10];
    while( scanf("%d", &n) != EOF)
    {
        for(int i = 0; i < n; i++)
            scanf("%lld %lld",&a[i],&r[i] );
        printf("%lld\n", Modline( r, a, n ) );    
    }
    return 0;
}

 

posted @ 2013-01-03 14:40  yefeng1627  阅读(290)  评论(0编辑  收藏  举报

Launch CodeCogs Equation Editor