如何使用 GMP 计算 2 ^ -18?

2024-01-31

令我尴尬的是,我刚刚发现,给负指数喂食mpz_pow_ui效果不太好。 (“手册确实说 unsigned long,你知道。”)对于另一个mpz_pow功能,手册使用了我不理解的概念。例如 ”base^exp mod mod“ 在下面的:

void mpz_powm (mpz_t rop, mpz_t base, mpz_t exp, mpz_t mod) 
void mpz_powm_ui (mpz_t rop, mpz_t base, unsigned long int exp, mpz_t mod)
Set _rop_ to _base_^_exp_ mod _mod_.
Negative exp is supported if an inverse base-1 mod mod exists (see mpz_invert in Section 5.9 [Number Theoretic Functions], page 35). If an inverse doesn’t exist then a divide by zero is raised.

在下面的代码中,我需要更改什么才能使其能够处理负指数?

#define Z(x) mpz_t x; mpz_init( x );

BSTR __stdcall IBIGPOWER(BSTR p1, long p2 ) {
    USES_CONVERSION;

    Z(n1);
    Z(res);

    LPSTR sNum1 = W2A( p1 );

    mpz_set_str( n1, sNum1, 10 );

    mpz_pow_ui( res, n1, p2 );

    char * buff =  (char *) _alloca( mpz_sizeinbase( res, 10 ) + 2 );

    mpz_get_str(buff, 10, res);

    BSTR bResult = _com_util::ConvertStringToBSTR( buff );
    return bResult;
}

我不会为您删除代码,但我会让您意识到:

2-n = 1/2n

So you can just pass the positive exponent then divide 1 by that number (and choose a non-integer type like mpf_t - the mpz_t type is integral so cannot represent real numbers like 2-18).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 GMP 计算 2 ^ -18? 的相关文章

随机推荐