C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

ミドルスクエア法を使用して乱数を生成するC++プログラム


ミドルスクエア法は、乱数を生成する最も簡単な方法の1つです。このメソッドは、同じ番号の生成を繰り返し開始するか、シーケンス内の前の番号に循環して、無期限にループします。 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, .........

  1. 配列を使用して数値の平均を計算するC++プログラム

    数値の平均は、すべての数値を加算し、その合計を使用可能な数値の数で割ることによって計算されます。 この例は次のとおりです。 The numbers whose average is to be calculated are: 10, 5, 32, 4, 9 Sum of numbers = 60 Average of numbers = 60/5 = 12 配列を使用して数値の平均を計算するプログラムは次のとおりです。 例 #include <iostream> using namespace std; int main() {    int n, i; &

  2. 安全な乱数を生成するC#プログラム

    安全な乱数を得るには、RNGCryptoServiceProviderクラスを使用します。暗号化乱数ジェネレーターを実装しています。 同じクラスを使用して、次の-を使用していくつかのランダムな値を見つけました using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {    byte[] val = new byte[6];    crypto.GetBytes(val);    randomvalue = BitConverter.ToInt