使用中间平方法生成随机数的 C++ 程序

中平方法是最简单的随机数生成方法之一。此方法将开始重复生成相同的数字或循环到序列中的前一个数字并无限循环。对于 ndigit 随机数的生成器,周期不能长于 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 << "输入您想要的数字随机数: ";
   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 << ".........";
}
输出结果
输入您想要的数字随机数: 4
The random numbers are: 6383, 14846, 8067, 51524, .........