首页 > 解决方案 > 如何修复适用于某些值但不适用于其他值的代码

问题描述

当我输入一些值时,我得到了答案,但其他值没有,系统保持阻塞

int pgcdfon(mpz_t a, mpz_t b, mpz_t *x, mpz_t *y) {
    if (mpz_cmp_ui(a, 0) == 0) {
        mpz_set_ui(*x, 0);
        mpz_set_ui(*y, 1);
        return b;
    }
    mpz_t x1, y1, res, h;
    mpz_init(x1);
    mpz_init(y1);
    mpz_init(res);
    mpz_t o;
    mpz_init(o);
    mpz_init(h);
    mpz_mod(res, b, a);
    int pgcd = pgcdfon(res, a, &x1, &y1);
    mpz_div(o, b, a);
    mpz_mul(h, o, x1);
    mpz_sub(*x, y1, h);
    mpz_set(*y, x1);
    return pgcd;
}

void main() {
    mpz_t x, y, q, w, g;
    mpz_init(x);
    mpz_init(y);
    mpz_init(q);
    mpz_init(w);
    mpz_init(g);
    gmp_printf("donner q \n ");
    gmp_scanf("%Zd", &q);
    gmp_printf("donner w \n");
    gmp_scanf("%Zd", &w);
    mpz_set(g, (pgcdfon(q, w, &x, &y)));
    gmp_printf("\n\n pgcd  de (%Zd, %Zd) = %Zd  \n\n", q, w, g);
}

标签: cgmp

解决方案


该类型mpz_t是(伪装的)数组类型,因此不能从函数返回。您必须更改函数的原型以返回参数中的值out,而不是返回它。这意味着,像

mpz_t myfun (...) {
     mpz_t ret;
     mpz_init(ret);

     // fill ret with someting

     return ret;
}

不能工作,但必须重写为:

void myfun (..., mpz_t *out) {
     mpz_t ret;
     mpz_init(ret);

     // fill ret with stuff
     mpz_init(*out); // if not initialized by caller
     mpz_set(*out, ret);
}

应用于您的函数的这种技术会产生

void pgcdfon(mpz_t a, mpz_t b, mpz_t *x, mpz_t *y, mpz_t *ret) {
    if (mpz_cmp_ui(a, 0) == 0) {
        mpz_set_ui(*x, 0);
        mpz_set_ui(*y, 1);
        mpz_init(*ret);
        mpz_set(*ret, b);
        return;
    }
    mpz_t x1, y1, res, h;
    mpz_init(x1);
    mpz_init(y1);
    mpz_init(res);
    mpz_t o;
    mpz_init(o);
    mpz_init(h);
    mpz_mod(res, b, a);
    mpz_t pgcd;
    pgcdfon(res, a, &x1, &y1, &pgcd);
    mpz_div(o, b, a);
    mpz_mul(h, o, x1);
    mpz_sub(*x, y1, h);
    mpz_set(*y, x1);
    mpz_init(*ret);
    mpz_set(*ret, pgcd);
}

int main() {
    mpz_t x, y, q, w, g;
    mpz_init(x);
    mpz_init(y);
    mpz_init(q);
    mpz_init(w);
    mpz_init(g);
    gmp_printf("donner q \n ");
    gmp_scanf("%Zd", &q);
    gmp_printf("donner w \n");
    gmp_scanf("%Zd", &w);
    pgcdfon(q, w, &x, &y, &g);
    gmp_printf("\n\n pgcd  de (%Zd, %Zd) = %Zd  \n\n", q, w, g);
}

这应该可以按您的预期工作。


推荐阅读