cgmp

Valid parameters for GMP's mpz_mod_ui


The documentation of mpz_mod_ui states it's interface as:

unsigned long int mpz_mod_ui (mpz_t r, const mpz_t n, unsigned long int d);

That essentially computes r = n % d, which is a non-negative integer less than d, also the function result; or cause a division by zero if d == 0.

Is it OK to set the r parameter to NULL, meaning we do not need an mpz_t set to the result?

In C, unsigned long int is not fixed size. It's at-least-32-bit, but is often 64-bit. Is GMP supported on platforms with various size of unsigned long int? Is the largest valid d always ~0UL (or I think equivalently ULONG_MAX defined in <limits.h> of a C compiler) on all supported platforms?


Solution

  • When using mpz_mod_ui, is it OK to set the r parameter to NULL, meaning we do not need an mpz_t set to the result?

    That's not advisable, and there's a better way. As noted in comment, there is a function computing n % d for d that fits an unsigned long int:

    unsigned long int mpz_fdiv_ui (const mpz_t n, unsigned long int d);
    

    Is GMP supported on platforms with various size of unsigned long int?

    Yes. As noted in another comment, unsigned long can be 64-bit or 32-bit depending on GMP compilation parameters, see the ABI and ISA documentation. However 64-bit unsigned long int is increasingly supported, and is available on each supported platforms in at least one option.