Pseudo random number using the Middle Square Method

The Middle Square Method produces random numbers based on the square of a number. Mostly random number generators are not all good algorithms, but the Middle Square Method is a widely used algorithm used to generate numbers in cryptographic algorithms; it was created by John von Neumann to generate a sequence of 4-digit random numbers. It takes the square of the seed to make it an 8-bit number, if not 8 bits, add zeroes to the start to make it an 8-bit number. After making it an 8-bit number, take the middle 4 digits. We have a new random number, and the process goes on.

Middle Square Logic

Explanation

In the illustration above, we have a 4-digit number, 2135; the algorithm takes it square which is a 7-bit number. It makes it 8-bit by adding a 0 to the start and taking the middle 4 digits gives us a random number. This number is now the new seed, and Middle Square Method will use to generate more numbers.

Example

In the code widget below, we have the implementation of the Middle Square Method in python.

seed = 2135
def random():
global seed
s = str(seed ** 2)
while len(s) != 8:
s = "0" + s
seed = int(s[2:6])
return seed
for i in range(0,5):
print(random())

Explanation

  • Line 1: We declare the seed.

  • Lines 2-4: We make a function that implements the Middle Square Method.

  • Lines 5-7: It adds the zeroes to the start to make it an 8-bit number and takes the middle 4-digit number.

Copyright ©2024 Educative, Inc. All rights reserved