Making Random Numbers

Interview

Time limit1sMemory limit256 MB

Summary
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 a0a_0. When written in decimal, a0a_0 must have at most nn digits. Next, square a0a_0 and pad the result with leading zeros until it has 2n2n digits. The middle nn digits of this 2n2n-digit number become a1a_1. Repeating the same rule yields aia_i for every i>0i > 0. In this problem, n=4n = 4 is fixed.

Example 1: If a0=5555a_0 = 5555, then a02=30858025a_0^2 = 30858025, so taking the middle four digits gives a1=8580a_1 = 8580.

Example 2: If a0=1111a_0 = 1111, then a02=01234321a_0^2 = 01234321 (padded with a leading zero to eight digits), so a1=2343a_1 = 2343.

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 a0a_0, 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 a0a_0 (0<a0<100000 < a_0 < 10000). If a0a_0 does not have four digits, it is written with leading zeros to make four digits. The last line of the input contains a single 00, which is not processed.

Output

For each test case, print on one line the number of distinct values aia_i that appear in the sequence. Count a0a_0 as well.

Examples1

  1. Example 1

    Input
    5555
    0815
    6239
    0
    
    Expected output
    32
    17
    111