mini-gmp "bug" missing mpz_fits_sint_p / mpz_fits_uint_p
Marco Bodrato
bodrato at mail.dm.unipi.it
Sun Apr 19 09:46:25 UTC 2020
Il 2020-04-19 10:44 nisse at lysator.liu.se ha scritto:
> Marco Bodrato <bodrato at mail.dm.unipi.it> writes:
>
>> +int
>> +mpz_fits_sint_p (const mpz_t u)
>> +{
>> + return (INT_MAX + INT_MIN == 0 || mpz_cmp_ui (u, INT_MAX) <= 0) &&
>> + mpz_cmpabs_ui (u, GMP_NEG_CAST (unsigned long int, INT_MIN)) <=
>> 0;
>> +}
>
> I think this and mpz_fits_sshort_p would be simpler using mpz_cmp_si,
>
> int
> mpz_fits_sint_p (const mpz_t u)
> {
> return mpz_cmp_si (u, INT_MAX) <= 0 && mpz_cmp_si (i, INT_MIN) >= 0;
> }
The current implementation of _cmp_si in mini- is:
mpz_cmp_si (const mpz_t u, long v)
{
mp_size_t usize = u->_mp_size;
if (v >= 0)
return mpz_cmp_ui (u, v);
else if (usize >= 0)
return 1;
else
return - mpz_cmpabs_ui (u, GMP_NEG_CAST (unsigned long int, v));
}
So that the compiler may optimise your code to:
return mpz_cmp_ui (u, INT_MAX) <= 0 &&
(u->_mp_size >= 0 ||
mpz_cmpabs_ui (u, GMP_NEG_CAST (unsigned long int, INT_MIN)) <=
0) ;
which basically is the condition I wrote, with one more branch.
> BTW, do we have any C implementation where INT_MAX + INT_MIN == 0,
> i.e.,
> not using two's complement?
I'm almost sure the compiler can optimise that out at compile time.
Ĝis,
m
More information about the gmp-devel
mailing list