Generate Random Numbers Using Middle Square Method in Java
This method was proposed by Van Neumann. In this method, we have a seed and then the seed is squared and its midterm is fetched as the random number. Consider we have a seed having N digits we square that number to get a 2N digits number if it doesn’t become 2N digits we add zeros before the number to make it 2N digits. A good algorithm is basically the one which does not depend on the seed and the period should also be maximally long that it should almost touch every number in its range before it starts repeating itself as a rule of thumb remember that longer the period more random is the number.
Consider the seed to be 14 and we want a two digit random number. Number --> Square --> Mid-term 14 --> 0196 --> 19 19 --> 0361 --> 36 36 --> 1296 --> 29 29 --> 0841 --> 84 84 --> 7056 --> 05 05 --> 0025 --> 02 02 --> 0004 --> 00 00 --> 0000 --> 00
In the above example, we can notice that we get some random numbers 19,36,29,84,05,02,00 which seem to be random picks, in this way we get multiple random numbers until we encounter a self-repeating chain. We also get to know a disadvantage of this method that is if we encounter a 0 then we get a chain of 0s from that point. Also, consider that we get a random number 50 the square will be 2500 and the midterms are 50 again, and we get into this chain of 50, and sometimes we may encounter such chains more often which acts as a disadvantage and because of these disadvantages this method is not practically used for generating random numbers.
The random numbers for the Geeks are: 325, 562, 584, 105, 102, 40, 160, 560, 360, 960,
Note: The above program shows how the Middle Square Number method works you can run the program multiple times to see different random numbers generated every time. And this method is not recommended as an ideal way of generating random numbers due to its disadvantages but this method can be used as a hashing algorithm and some other applications too.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.