Prime number based quadratic probing function only hits every location for m == (specific prime)

84 Views Asked by At

I have a hash_probe function which takes a hash value, an index and an capacity to get the probe index by quadratic probing. I dont know why but as I tried different capabilities like 3, 5, 7, 11, 13, 17, 23 I saw that I would only hit every location from n to cap for cap == 3, 7, 11, 23.

Regarding to the answer by user "templatetypdef" and Wikipedia Examples of Quadratic Probing

You can try it below by changing TEST_PRIME macro to any prime number. What do I missunderstand or why does it work with 3, 7, 11, 23 but not with 5, 13, 17?

Example output for Cap == 7 (as expected):

4
3
1
2
6
0
5

Example output for Cap == 5 (not as aspected):

0
4
4
1
1
#include <stdio.h>
#include <string.h>

// hashes str until nullbyte is found
size_t djb2(const char *str)
{
    /* djb2 offset 5381 */
    unsigned long hash = 5381;
    int c;

    while ((c = *str++))
        hash = ((hash << 5) + hash) + (size_t) c; /* hash * 33 + c */

    return hash;
}

// calculates the probe index by hash, index and capability
size_t hash_probe(unsigned long hash, size_t i, size_t cap)
{

    size_t idx = 0;

    if(i & 1) { // odd
        idx = (hash + -(i*i)) % cap;
    } else {
        idx = (hash + (i*i)) % cap;
    }
    return idx;
}

#define TEST_PRIME 23

int main(void)
{
    // get hash
    unsigned long hash = djb2("Hallo Welt!\n");
    
    // loop though 0 to TEST_PRIME and print its probe index value
    for(size_t i = 0; i < TEST_PRIME; i++) {
        size_t idx = hash_probe(hash, i, TEST_PRIME);
        printf("%zu\n", idx);
    }

    return 0;
}
0

There are 0 best solutions below