扩展欧几里得

hdoj 1576 A/B

(A/B)%C = (A*B^-1)%C = (A%C)*(B^-1)%C

用扩展欧几里得求出B的逆元B^-1 

//x是a mod b的乘法逆元,y是b mod a的乘法逆元
inline int extend_gcd( int a, int b, int &x, int &y ) {
    int tp, r;
    if( b == 0 ) {
        x = 1;
        y = 0;
        return a;
    }

    r = extend_gcd( b, a%b, x, y );
    tp = x;
    x = y;
    y = tp - a / b * y;
    return r;
}

 AC代码:

#include <iostream>
using namespace std;

int mod = 9973;

//求x是a mod b的乘法逆元,y是b mod a的乘法逆元
inline int extend_gcd( int a, int b, int &x, int &y ) {
    int tp, r;
    if( b == 0 ) {
        x = 1;
        y = 0;
        return a;
    }

    r = extend_gcd( b, a%b, x, y );
    tp = x;
    x = y;
    y = tp - a / b * y;
    return r;
}


int main() {
//    freopen( "c:/aaa.txt", "r", stdin );
    int T, n, b, x, y;
    scanf( "%d", &T );
    while( T-- ) {
        scanf( "%d %d", &n, &b );
        extend_gcd( b, mod, x, y );
        x = ( (x*n%mod) + mod) % mod;
        printf( "%d\n", x );
    }
    return 0;
}

.

posted on 2011-03-12 21:58  CrazyAC  阅读(299)  评论(0编辑  收藏  举报