gpt-3.5-turbo-0125· OpenAI
WildChat-4.8M (AI2)
Write mid-square hash function in C++
- User
Write mid-square hash function in C++
- Assistant
Here is an implementation of a mid-square hash function in C++:
#include <iostream> #include <cmath> unsigned int midSquareHash(unsigned int key, int tableSize) { unsigned int square = key * key; std::string squareStr = std::to_string(square); int startPos = squareStr.length() / 2 - tableSize / 2; std::string hashStr = squareStr.substr(startPos, tableSize); return std::stoi(hashStr); } int main() { unsigned int key = 12345; int tableSize = 5; unsigned int hashValue = midSquareHash(key, tableSize); std::cout << "Hash value for key " << key << " is: " << hashValue << std::endl; return 0; }In this implementation, the
midSquareHashfunction takes a key and a table size as input parameters. It calculates the square of the key and extracts a substring from the middle of the square based on the table size. The resulting substring is then converted to an integer and returned as the hash value.In the
mainfunction, an example key and table size are specified, and the hash value for the key is computed and printed to the console.