扩展欧几里得

结果

代码

    #include <stdio.h>

struct EX_GCD { //s,t是系数,gcd是a,b的最大公约数
    int s;
    int t;
    int gcd;
};

struct EX_GCD extended_euclidean(int a, int b,int *k, int *u, int *v) {
    struct EX_GCD ex_gcd;

    k=ex_gcd.s;
    u=ex_gcd.t;
    v=ex_gcd.gcd;
    if (b == 0) { //b等于0时直接结束求解
        k = 1;
        u = 0;
        v = 0; 
        return ex_gcd;
    }
    int old_r = a, r = b;
    int old_s = 1, s = 0;
    int old_t = 0, t = 1;
    while (r != 0) { //按扩展欧几里得算法进行循环
        int q = old_r / r;
        int temp = old_r;
        old_r = r;
        r = temp - q * r;
        temp = old_s;
        old_s = s;
        s = temp - q * s;
        temp = old_t;
        old_t = t;
        t = temp - q * t;
    }
        ex_gcd.s = old_s;
    ex_gcd.t = old_t;
    ex_gcd.gcd = old_r;
    return ex_gcd;
    }

int main(void) {
    int a, b,k,u,v;
    printf("Please input two integers .\n");
    scanf("%d%d", &a, &b);
    if (a < b) { //如果a小于b,则交换a和b以便后续求解
        int temp = a;
        a = b;
        b = temp;
    }
    struct EX_GCD solution = extended_euclidean(a, b,&k,&u,&v);
    printf("%d*%d+%d*%d=%d\n", k, a, u, b, v);

    return 0;
}
posted @ 2022-06-09 15:23  20191301  阅读(32)  评论(0编辑  收藏  举报