C ++中的中平方哈希。

问题陈述

中平方方法是一种生成伪随机数的方法。该方法由约翰·冯·诺伊曼(John von Neumann)发明,并在1949年的一次会议上进行了描述。

  • 在该技术中,采用初始种子值并将其平方。

  • 从中间提取一些数字,这些提取的数字形成一个数字,该数字被当作新的种子。

    • 让我们以3456作为种子。其广场是11943936

    • 以中间的四位数作为新种子,即9439。其平方为89094721

    • 将中间的4位数字作为新种子,即0947

    • 重复这个过程

算法

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

示例

#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;
}

输出结果

当您编译并执行上述程序时。它生成以下输出-

Random number: 10088419