使用具有负指数的 GMP/MPIR 库中的mpz_powm函数

Using the mpz_powm functions from the GMP/MPIR libraries with negative exponents

本文关键字:mpz 函数 powm MPIR 负指数 GMP      更新时间:2023-10-16

请考虑以下代码:

mpz_t x, n, out;
mpz_init_set_ui(x, 2UL);
mpz_init_set_ui(n, 7UL);
mpz_init(out);
mpz_invert(out, x, n);
gmp_printf ("%Zdn", out);//prints 4. 2 * 4 (mod 7) = 1. OK
mpz_powm_ui(out, x, -1, n);//prints 1. 2 * 1 (mod 7) = 2. How come?
gmp_printf ("%Zdn", out);
mpz_clear(x);
mpz_clear(n);
mpz_clear(out);

我无法理解 mpz_powm 函数如何处理负指数,尽管根据文档,它应该支持它们。我希望将一个数字提高到 -1 模 n 等同于将其反转模 n。我在这里错过了什么?

尝试将 -1 设为有符号数字。换句话说,不要使用无符号接口,而是用值 -1 制作真正的 bignum。

即:

#include <gmpxx.h>
#include <iostream>
int main()
{
    mpz_class n(7), k(2), res;
    mpz_powm(res.get_mpz_t(), k.get_mpz_t(), mpz_class(-1).get_mpz_t(), n.get_mpz_t());
    std::cout << res << std::endl;
}

指纹:

4

该问题是由声明mpz_powm_ui函数的方式引起的:

void mpz_powm_ui (mpz t rop, mpz t base, unsigned long int exp, mpz t mod)

也许这是一个文档错误,因为exp总是积极的。