C++ 程序使用平方中间法生成随机数
平方中间法是最简单的随机数生成方法之一。此方法将开始反复生成相同数字,或循环到序列中的前一个数字,并无限循环。对于一个 n 位随机数生成器,周期长度不会超过 n。如果中间 n 位都为零,生成器会一直输出零,虽然这些零的序列很容易检测到,但它们的出现过于频繁,以至于无法通过此方法进行实际使用。
Input − Enter the digit for random number:4 Output − The random numbers are: 6383, 14846, 8067, 51524, .........
算法
Begin middleSquareNumber(number, digit) Declare an array and assign next_number=0. Square the number and assign it to a variable sqn. Divide the digit by 2 and assign it to a variable t. Divide sqn by a[t] and store it to sqn. For i=0 to digit, do next_number =next _number (sqn mod (a[t])) * (a[i]); sqn = sqn / 10; Done Return the next number End.
代码示例
#include <iostream> using namespace std; int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 }; int middleSquareNumber(int number, int digit) { int sqn = number * number, next_number = 0; int t = (digit / 2); sqn = sqn / a[t]; for (int i = 0; i < digit; i++) { next_number += (sqn % (a[t])) * (a[i]); sqn = sqn / 10; } return next_number; } int main(int argc, char **argv) { cout << "Enter the digit random numbers you want: "; int n; cin >> n; int start = 1; int end = 1; start = a[n - 1]; end = a[n]; int number = ((rand()) % (end - start)) + start; cout << "The random numbers are:\n" << number << ", "; for (int i = 1; i < n; i++) { number = middleSquareNumber(number, n); cout << number << ", "; } cout << "........."; }
输出
Enter the digit random numbers you want: 4 The random numbers are: 6383, 14846, 8067, 51524, .........
广告