C++ Program to Generate Random Numbers using Middle Square Method

This is a C++ Program to generate random numbers using Middle Square method. In mathematics, the middle-square method is a method of generating pseudorandom numbers. In practice it is not a good method, since its period is usually very short and it has some severe weaknesses, such as the output sequence almost always converging to zero.

Here is source code of the C++ Program to Generate Random Numbers Using Middle Square Method. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <iostream>
  2. #include <math.h>
  3. #include <stdlib.h>
  4.  
  5. using namespace std;
  6.  
  7. int a[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000 };
  8. int middleSquareNumber(int numb, int dig)
  9. {
  10.     int sqn = numb * numb, next_num = 0;
  11.     int trim = (dig / 2);
  12.     sqn = sqn / a[trim];
  13.     for (int i = 0; i < dig; i++)
  14.     {
  15.         next_num += (sqn % (a[trim])) * (a[i]);
  16.         sqn = sqn / 10;
  17.     }
  18.     return next_num;
  19. }
  20.  
  21. int main(int argc, char **argv)
  22. {
  23.     cout << "Enter the #-digit random numbers you want: ";
  24.     int n;
  25.     cin >> n;
  26.     int start = 1, end = 1;
  27.  
  28.     start = a[n - 1];
  29.     end = a[n];
  30.  
  31.     int number = ((rand()) % (end - start)) + start;
  32.     cout << "The random numbers are:\n" << number << ", ";
  33.     for (int i = 1; i < n; i++)
  34.     {
  35.         number = middleSquareNumber(number, n);
  36.         cout << number << ", ";
  37.     }
  38.     cout << "...";
  39. }

Output:

$ g++ MiddleSquare.cpp
$ a.out
 
Enter the #-digit random numbers you want: 5
The random numbers are:
10041, 16426, 796264, -276041, -115546, ...

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement

Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.