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, .........

最後更新:2019 年 7 月 30 日

1K+ 檢視

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告