Search code examples
constantsgmp

Is there a zero constant in the GMP library?


In a program, I have to check whether a certain number is equal to zero. One way to do it is to just initialise an mpz_t and check whether the original number equals it. But surely there is a zero constant in GMP, like BigInteger.ZERO in Java & Kotlin?

(Somehow this page doesn't contain what I want; I did "check the fine manual" & use a search engine, for those of you who adhere to the standard level of politeness on this page.)

Thank you very much in advance!

EDIT: I just learned that one may compare an mpz_t to an integer, so that one may do something like mpz_cmp_ui(variable, 0) == 0. The solutions given by the answer by Marc Glisse are probably even faster.


Solution

  • To test if z is zero, you can test mpz_sgn(z)==0 or mpz_size(z)==0, you don't need an mpz_t with value 0. As you noticed, you can also compare z to a native integer with mpz_cmp_ui or mpz_cmp_si.

    There is no predefined constant 0. Calling mpz_init is cheap enough (no allocation) to create a zero if you need one.