Principles refer to "Introduction to Algorithms"
One, the division hash function
Implement the algorithm according to the description, first take the corresponding seed
int hash_mod_seed( int n, int iCheck) { // Store n keywords, an unsuccessful search needs to check iCheck keywords, the default one character is 8 bits int iStart= n / iCheck, prime = (iStart == 1 ) ? 2 : iStart; assert(iCheck >= 0 && iCheck <= 8 ); // The odd start should skip the already judged odd number for ( int j = 0 , odd = (iStart % 2 == 0 ) ? iStart / 2 : (iStart - 1 ) / 2 + 1 ; j < 8 - iCheck; odd++ ) { // generate a prime number bool fPrime = true ; for ( int k = 2 ; k <= sqrt(prime); k++ ) if (prime % k == 0 ) { fPrime = false; break; } if (fPrime) // Record the prime number j++ ; prime = odd * 2 + 1 ; // odd number to be determined } return prime - 2 ; }
Key Algorithm Implementation
int hash_mod(int key, int seed) { return key % seed; }
2. Multiplicative Hash Function
Implemented according to the algorithm description
int hash_mul( int key, int w, int p) { // w means that the keyword int is 32 bits, and p is the most significant bit truncated after mapping __int64 s = (sqrt( 5 ) - 1 ) / 2 * pow( 2 , w); __int64 r0 = s*key % ( int )pow( 2 , w); return r0 / pow( 2 , w - p); // high p significant bits }
All code is tested and the result is correct