欧几里得算法和扩展欧几里得算法的简单例子

欧几里得算法:

#include 
#include 

/*
*   挑战。。。p113
*/

struct point{   //格点
    int x;
    int y;
};

point p1, p2;   //两个格点

int gcd(int a,int b){   //欧几里得算法
    if(b == 0) {
        return a;
    } else {
        return gcd(b, a % b);
    }
}

void solve(){
    int px = abs(p1.x - p2.x);  //两格点的x坐标距离
    int py = abs(p1.y - p2.y);  //两格点的y左边距离
    int res = 0;
    if(px != 0 && py != 0){
        res = gcd(px, py) - 1;
    }
    printf("%d\n", res);
}


int main(){
    while(scanf("%d%d%d%d", &p1.x, &p1.y, &p2.x, &p2.y) != EOF){
        solve();
    }
    return 0;
}

扩展欧几里得算法:

#include 

/*
*   挑战程序设计竞赛 p115
/*

//思路:
//扩展欧几里得算法是在欧几里得的算法基础上求解模线性方程及方程组
//已知ax + by = 1,gcd(a, b) = 1
//所以ax + by = gcd(a, b) ①
//再辗转相除一次后,①变为②
//bx + (a % b)y = gcd(a, b) ②
//a % b = a - (a / b) * b ③
//将③代入②得到④
//bx + (a - (a / b) * b)y = gcd(a, b) ④
//将④化简为⑤
//ay + b(x - (a / b) * y) = gcd(a, b) ⑤

//当b = 0时,显然有 a = gcd(a , b),这时 x = 1, y = 0
//总之,有如下几个等式
// 当 b = 0 时,x = 1, y = 0
// 其他情况 x = y, y = (x - (a / b) * y)

int a,b;
int x,y;
int extgcd(int a, int b, int &x, int &y){ //扩展欧几里得算法
    if(b == 0){
        x = 1;
        y = 0;
        return a;
    } else {
        int r = extgcd(b, a % b, x, y);
        int t = x;
        x = y;
        y = t - (a / b) * y;
        return r;
    }
}

void solve(){
    int res = extgcd(a, b, x, y);
    if(res != 1){
        printf("-1\n");
        return;
    }
    if(x > 0){
        printf("%d0", x);
    } else {
        printf("0%d", -x);
    }
    if(y > 0){
        printf("%d0\n", y);
    } else {
        printf("0%d\n", -y);
    }
}

int main(){
    while(scanf("%d%d", &a, &b) != EOF){
        solve();
    }
}



你可能感兴趣的:(ACM)