Generate Random Numbers Using Middle Square Method in Java

Computing random numbers is considered to be one of the basic requirements of any computer application it is employed in fields that include cryptography, simulations, and games. Random numbers are real numbers undetermined by prior events whereas pseudo random numbers are produced through deterministic methods and are almost random. Middle Square Method is one of the oldest ways of developing the approximation of pseudo-random numbers.

The Middle Square Method first defined by John von Neumann in 1949 is a very simple but quite historical in terms of concepts. In this form of pattern, one squares a number and uses the two middle numbers from the squared result as the following number in the sequence. However, the above mentioned method is not without its drawbacks and can easily get stuck in -ve cycles as soon as it starts or turns out to be a zero sum game. Although, it is helpful when learning the rudimentary concepts of random number generation.

How to Use Middle Square Method?

Start with a Seed: The first operation specifies that the seed has to be a positive integer and it must contain an even digits count.

Square the Seed: Multiply the seed by it self.

Extract Middle Digits: The next number is obtained by picking the middle digits from the squared result.

Repeat: Take the extracted number as the new seed or simply repeat the whole process.

For example, if we start with a seed of 1234:

Square it: 1234*1234=1522756

Extract the middle 4 digits: 2275

It means the use of 2275 as the new seed and go round again.

File Name: MiddleSquareMethod.java

Output:

5227
3215
3362
3030
1809
2724
4201
6484
422
1780
241383
265752
624125
532015
39960
596801
171433
389273
533468
588107

Explanation:

It contains a class MiddleSquareMethod with a constructor with a 'seed' parameter to set the first value for generating the sequence and a method 'next()' to generate the next value in the sequence. It should be a positive integer and the number of digits in the seed must be even.

The next procedure has a parameter, numDigits, that defines how many middle digits should be taken from the square of a seed. This value is squared, and the resulting value is lexicographically left-padded with the numeral zero to make it at least 2 * numDigits digits long. The middle digits are then extracted and used as the new seed They are then extracted to use as the new seed.

The primary method illustrates the use of the class by creating and displaying ten random numbers with middle digits of 4 and 6 , seeded with 1234 and 123456 respectively. If an incorrectly chosen seed or number of digits is entered, an IllegalArgumentException appears and is caught, displaying an error message.