[Routed] Hash function for mpz_class.

Dmitry Panteleev dpantele at dpantele.com
Sat Jul 19 14:18:32 UTC 2014


Hello Fernando,

First of, it depends of the nature of your numbers. Because if you
have absolutely uniformly distributed numbers, you can simply take the
0 limb, like this(*):

namespace std {
template <> struct hash<mpz_class>
{
  size_t operator()(const mpz_class& x) const
  {
    return x.get_mpz_t()[0]._mp_size != 0 ?
static_cast<size_t>(x.get_mpz_t()[0]._mp_d[0]) : 0;
  }
};
}

(*) I have no machine with gmp right now, I haven't tested the code

If it is worse, you have to use some data-hashing function, like
cityhash, murmurhash or a SipHash. The interface of all of them is
almost the same, so here is for the cityhash:

namespace std {
template <> struct hash<mpz_class>
{
  size_t operator()(const mpz_class& x) const
  {
    //hashing mpz limbs, signed size serves as a seed
    return CityHash64WithSeed(static_cast<const
char*>(x.get_mpz_t()[0]._mp_d), sizeof(mp_limb_t) *
abs(x.get_mpz_t()[0]._mp_size), x.get_mpz_t()[0]._mp_size);
  }
};
}

I am not sure if my way of accessing mpz_struct fields is good, but
everything else should work.

Best,
Dmitry

On Fri, Jul 18, 2014 at 9:51 PM, Fernando Alberione
<falberione037 at gmail.com> wrote:
> Hello,
>    writing this mail because I need information on how to build a hash
> function for:
>
> std::unordered_set<mpz_class> set;
>
> Thanks!
> _______________________________________________
> gmp-discuss mailing list
> gmp-discuss at gmplib.org
> https://gmplib.org/mailman/listinfo/gmp-discuss



-- 
Best Regards,
Dmitry Panteleev


More information about the gmp-discuss mailing list