分享一個比官方快10倍的隨機數算法, 經過測試, 一次性可產生40億個不同的隨機數
程序代码:
#include <stdio.h> #include <stdlib.h> int rand2(int min, int max) { static unsigned long long z = 1, d = 0, s = 0, i = 256; static unsigned char* zz = (unsigned char*)&z, * dd = (unsigned char*)&d, *ss = (unsigned char*)&s; if ((++i) >= 256) { if (d) free((void*)d); d = (unsigned long long)malloc(8); i = 0; } // 產生隨機堆位址到d z = z * 17 + 139; // 線性求餘法產生0~256之間的隨機數到z ss[0] = zz[0] + dd[0] + dd[7] + ss[3]; // 隨機數和堆位址混合到ss ss[1] = zz[1] + dd[1] + dd[6] + ss[0]; ss[2] = zz[2] + dd[2] + dd[5] + ss[1]; ss[3] = zz[3] + dd[3] + dd[4] + ss[2]; return (int)(s % ((long long)max - min) + min); } int main() { int max = 100; do for (int i = 0; i < max; i++) printf(i % 10 == 0 ? "\n%d\t" : "%d\t", rand2(0, max)); while (printf("\n\n按回車鍵繼續:"), getchar() == '\n'); return 0; }