Mid-Square hashing in C++.

C++Server Side ProgrammingProgramming

Problem statement

The mid-square method is a method of generating pseudorandom numbers. This method was invented by John von Neumann and was described at a conference in 1949

  • In this technique, an initial seed value is taken and it is squared.

  • Some digits from the middle are extracted and these extracted digits form a number which is taken as the new seed.

    • Let us take 3456 as seed. Its square is 11943936

    • Take the middle 4 digits as new seed i.e. 9439. Its square is 89094721

    • Take middle 4 digits as new seed i.e. 0947

    • Repeat this process

Algorithm

1. Choose initial seed value
2. Take the square of the seed value
3. Update seed by taking n digits from previous result

Example

#include <iostream>
#include <ctime>
using namespace std;
long long getTime(){
   time_t t = time(NULL);
   struct tm *tm = localtime(&t);
   long long x = (tm->tm_hour) * 50000000 + (tm->tm_min) * 100000 + (tm->tm_sec) * 5000 +
(tm->tm_mday) * 50 + (tm->tm_year);
   return x;
}
long getHash(){
   long long key = getTime();
   key = key * key;
   key = key / 10000;
   key = key % 100000000;
   return key;
}
int main(){
   cout << "Random number: " << getHash() << endl;
   return 0;
}

Output

When you compile and execute the above program. It generates the following output−

Random number: 10088419
raja
Published on 31-Oct-2019 10:26:52
Advertisements