hash of mpz_t and mpq_t

Hans Åberg haberg-1 at telia.com
Tue Jun 15 12:56:52 UTC 2021


> On 15 Jun 2021, at 10:25, Torbjörn Granlund <tg at gmplib.org> wrote:
> 
> Mathieu Dutour <mathieu.dutour at gmail.com> writes:
> 
>  would it be possible to have a hash function defined on
>  GMP integers and rationals?
> 
>  This would be useful for building hash tables using gmp numeric.
> 
> For mpz_t, have you considered using mpz_export to a byte vector and
> then hash that?
> 
> And for mpq_t, the numref and denref with mpz_export?

For C++, with
  class integer { mpz_t value_; …}
I use:

namespace std {
  template<> struct hash<gmp::integer> {
    size_t operator()(gmp::integer const& x) const {
      std::size_t h = 0;
      for (int i = 0; i < abs(x.value_->_mp_size); ++i)
        h ^= std::hash<mp_limb_t>()(x.value_->_mp_d[i]);
      return h;
    }
  };

Possibly, it may not be stable because of calling GMP internals, so there might be a point in adding that.




More information about the gmp-discuss mailing list