求gcd(a,b) = ax + by中的gcd(a, b)、a、b(扩展欧几里得算法尾递归版)

转载注明出处,原文地址:http://blog.csdn.net/powerwoo25/article/details/47434071

求gcd(a,b) = ax + by中的gcd(a, b)、a、b(扩展欧几里得算法尾递归版)

思路:就是扩展欧几里得方法的C语言算法版。写了指针版跟非指针版,指针版可读性没有非指针版好,但是效率有所提高。只贴指针版好了。

转载注明出处,原文地址:http://blog.csdn.net/powerwoo25/article/details/47434071
/* 扩展欧几里得算法 */
typedef struct euclid_three_tuple
{
    int d, x, y;

    euclid_three_tuple(): d(0), x(0), y(0){};

}triTuple;

void ExtendedEuclid(unsigned int a, unsigned b, triTuple *res)
{
    if(b == 0)
    {
        res->d = a; res->x = 1; res->y = 0;
        return;
    }

    else
    {
        ExtendedEuclid(b, a%b, res);
        int oldX = res->x;
        res->x = res->y; res->y = oldX-a/b*res->y;
    }
}

#include 

int main()
{
    unsigned int m, n;
    while(~scanf("%d %d", &m, &n))
    {
        triTuple *ans = new triTuple;
        ExtendedEuclid(m, n, ans);
        printf("d = %d, x = %d, y = %d\n", ans->d, ans->x, ans->y);
        delete ans; ans = NULL;
    }
    return 0;
}


你可能感兴趣的:(算法设计)