Very low cost hash function

后端 未结 5 1997
死守一世寂寞
死守一世寂寞 2020-12-25 08:33

I need a hash function for a Look Up table, so that if my values are from 0 to N, I need a hash function that give me a value from 0 to n, being n << N. Another piece

5条回答
  •  心在旅途
    2020-12-25 09:26

    I believe this is the best possible hash for this problem (faster than modulo, better distribution), given that all your numbers in 0..N have the same probability:

    h = z * n / N;
    

    Where all values are integers, so you have an integer division. This way each value between 0..N is mapped to exactly the same number of values in n.

    For example, when n=3 and N=7 (values 3 and 7 not included in the ranges), the hashes are this:

    z * n / N = hash
    ----------------
    0 * 3 / 7 = 0
    1 * 3 / 7 = 0
    2 * 3 / 7 = 0
    3 * 3 / 7 = 1
    4 * 3 / 7 = 1
    5 * 3 / 7 = 2
    6 * 3 / 7 = 2
    

    So each hash values are used equally often, just off by 1. Just take care that n*(N-1) does not overflow.

    If N is a power of 2, you can replace the division by shifting. e.g. if N=256:

    h = (z * n) >> 8;
    

提交回复
热议问题