【问题标题】:Is there a c++ gmp library function that does the same as the python gmpy2 library divm(...) function?是否有与 python gmpy2 库 divm(...) 函数相同的 c++ gmp 库函数?
【发布时间】:2020-02-12 00:57:36
【问题描述】:

正如标题所说,我试图在 C++ gmp 库中找到一个与 gmpy2 python 库的 divm(...) 函数做同样事情的函数。

我无法想象 gmpy2 有这个方法,而 gmp C++ 库没有任何东西可以做同样的计算。

如果这不存在,我将不胜感激有关从头开始制作 divm 函数的任何建议(仍然必须使用 gmp,因为我正在通过 mpz_class 处理大于标准整数的值)。

谢谢!

【问题讨论】:

    标签: python c++ gmp gmpy


    【解决方案1】:

    该函数的 C 源代码可以在 here 中找到 GMPy_MPZ_Function_Divm。正如你所看到的,它并不是真正的与底层 C 代码的一对一映射,但是,当你去掉所有 Python 引用计数的东西时,它看起来非常基本:

    // numz, denz, and modz are copies of the arguments.
    // resz, gcdz ar temporaries.
    
    if (mpz_invert(resz, denz, modz)) {    // inverse exists?
        ok = 1;
    } else {                               // num, den AND mod have a gcd > 1?
        mpz_init(gcdz);
        mpz_gcd(gcdz, numz, denz);
        mpz_gcd(gcdz, gcdz, modz);
        mpz_divexact(numz, numz, gcdz);
        mpz_divexact(denz, denz, gcdz);
        mpz_divexact(modz, modz, gcdz);
        mpz_clear(gcdz);
        ok = mpz_invert(resz, denz, modz);
    }
    if (ok) {
        mpz_mul(resz, resz, numz);
        mpz_mod(resz, resz, modz);
        mpz_clear(numz);
        mpz_clear(denz);
        mpz_clear(modz);
        return resz;
    } else {
        mpz_clear(numz);
        mpz_clear(denz);
        mpz_clear(modz);
        return NULL;
    }
    

    在数学上,它只是为divm(a, b, m) 计算表达式b<sup>-1</sup> * a % m,当然假设该表达式是有效的(例如,b 不为零)。

    【讨论】:

      猜你喜欢
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 2019-07-02
      • 1970-01-01
      相关资源
      最近更新 更多