UVa 944 - Happy Numbers

944 - Happy Numbers

 * http://icpcres.ecs.baylor.edu/onlinejudge/external/9/944.html

Summary
Read two positive integers between 1 and 99999 (inclusive) each; the first integer, L, is the low limit of the closed interval; the second one, H, is the high limit (L ≤ H). The output is composed of the happy numbers that lie in the interval [L,H], together with the number of iterations required for the corresponding sequences of squares to reach 1.

Explanation
Instructions are clear. If you start with $$S_0 = 7$$

$$S_0 = 7$$

$$S_1 = 7^2 = 49$$

$$S_2 = 4^2 + 9^2 = 97$$

$$S_3 = 9^2 + 7^2 = 130$$

$$S_4 = 1^2 + 3^2 = 10$$

$$S_5 = 1^2 = 1$$

If you reach 1 then $$S_0$$ is Happy else it's Unhappy!

Gotcha's

 * $$S_0$$ is unhappy when you meet a $$S_i$$ again and it means a loop, so it never meets 1.
 * ``if $$S_0$$ is happy (unhappy), then any number in the sequence $$S_1, S_2 , S_3 , ...$$ will also be happy (unhappy) '' , attention , if you know $$S_i$$ is happy (unhappy) don’t waste time and terminate it because the rest of sequence will be happy (unhappy).
 * the number of iterations for $$S_0$$ ,if you meet a happy number in the sequence $$(S_i)$$, simply add the size of current sequence to the number of iterations for $$S_i$$, then $$S_1$$ = ( the number of iterations for $$S_0$$) - 1 and so on.

Input
7 10 1 7 10 4 10 10 1 1 99970 99999

Output
7 6 10 2

1 1 7 6

10 2

1 1

99971 7 99973 4 99978 8 99987 8