Making Random Numbers
InterviewTime limit1sMemory limit256 MB
Simulate the middle-square method with four-digit numbers and count how many distinct values appear before the first repeat.
- Level
Medium4 of 10
- Topics
- Simulation, Hash map, Implementation, Math
- Solved
- No attempts yet
Problem
In 1946, John von Neumann proposed a method for generating a sequence of pseudo-random numbers. It is known as the middle-square method and works as follows.
First, choose an initial value . When written in decimal, must have at most digits. Next, square and pad the result with leading zeros until it has digits. The middle digits of this -digit number become . Repeating the same rule yields for every . In this problem, is fixed.
Example 1: If , then , so taking the middle four digits gives .
Example 2: If , then (padded with a leading zero to eight digits), so .
In fact, this is not a good random number generator: the sequence eventually reproduces a value it has generated before and falls into a cycle.
Given , write a program that determines how many distinct numbers the sequence produces before it repeats a value for the first time.
Input
The input consists of several test cases. Each test case is a single line containing one integer (). If does not have four digits, it is written with leading zeros to make four digits. The last line of the input contains a single , which is not processed.
Output
For each test case, print on one line the number of distinct values that appear in the sequence. Count as well.