Knuth的乘法散列函数通过位移

时间:2015-02-11 20:24:36

标签: c++ algorithm hash

我试图通过位移来实现Knuth的乘法算法,A = 2654435769 和散列大小为2 ^ p个元素 但是非移位和移位算法给出了不同的结果

我试图实现这两个alg:



    template
    int mult_hash_simple(int key)
    {
        double A = 0.61803398863412439823150634765625;
        double exp = A*key;
        return max_key*(exp - (int) exp);
    }

    template
    int mult_hash_advanced(int key)
    {
    //  const int w = 32;
        const unsigned long long A = 2654435769;
        unsigned long long r0 = key*A;

        return r0 & (  (1 

UPD:更新了一些var类型。问题依然存在

1 个答案:

答案 0 :(得分:0)

下面的函数有高级哈希逻辑,它等于mult_hash_simple函数。

template<int max_key_power, int p>
int mult_hash_advanced(int key)
{
//  const int w = 32;
    const long long w_bit = 4294967295; // Integer representation of binary value that has last 32 ( which is w value )  bits as 1
    const int A = 2654435769; 
    long long r0 = key*A;


    return (( r0 & w_bit ) >> ( 32 - p ) ) ;
}
相关问题