# C++ Program to Generate Random Numbers Using Middle Square Method

The middle-square method is one of the simplest method of generating random numbers. this method will either begin repeatedly generating the same number or cycle to a previous number in the sequence and loop indefinitely. For a generator of ndigit random numbers, the period can be no longer than n. If the middle n digits are all zeroes, the Generator then outputs zeroes forever, while these runs of zero are easy to detect, they occur too frequently for this method to be of practical use.

Input − Enter the digit for random number:4
Output − The random numbers are: 6383, 14846, 8067, 51524, .........

## Algorithm

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.

## Example Code

#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 << ".........";
}

## Output

Enter the digit random numbers you want: 4
The random numbers are: 6383, 14846, 8067, 51524, .........