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