When is hash(n) == n in Python?

前端 未结 4 505
广开言路
广开言路 2021-01-30 05:08

I\'ve been playing with Python\'s hash function. For small integers, it appears hash(n) == n always. However this does not extend to large numbers:

         


        
4条回答
  •  轮回少年
    2021-01-30 05:20

    2305843009213693951 is 2^61 - 1. It's the largest Mersenne prime that fits into 64 bits.

    If you have to make a hash just by taking the value mod some number, then a large Mersenne prime is a good choice -- it's easy to compute and ensures an even distribution of possibilities. (Although I personally would never make a hash this way)

    It's especially convenient to compute the modulus for floating point numbers. They have an exponential component that multiplies the whole number by 2^x. Since 2^61 = 1 mod 2^61-1, you only need to consider the (exponent) mod 61.

    See: https://en.wikipedia.org/wiki/Mersenne_prime

提交回复
热议问题