C++中平方取中哈希。
问题陈述
平方取中法是一种生成伪随机数的方法。此方法是由约翰·冯·诺伊曼发明,并在 1949 年的一次会议上进行了描述
在该技术中,取一个初始种子值并对其进行平方。
从中间提取一些数字,这些提取的数字形成一个数字,该数字作为新的种子。
我们取 3456 作为种子。其平方是 11943936
取中间 4 位数字作为新的种子,即 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP