HPYNOS - Happy Numbers I

The process of “breaking” an integer is defined as summing the squares of its digits. For example, the result of breaking the integer 125 is (12 + 22 + 52) = 30. An integer N is happy if after “breaking” it repeatedly the result reaches 1. If the result never reaches 1 no matter how many times the “breaking” is repeated, then N is not a happy number.

TASK

Write a program that given an integer N, determines whether it is a happy number or not.

CONSTRAINTS

2 ≤ N ≤ 2,147,483,647

Input

A single line containing a single integer N.

Output

A single line containing a single integer T which is the number of times the process had to be done to determine that N is happy, or -1 if N is not happy.

Example

Input:
19

Output:
4
1) 19  : 12 + 92 = 82
2) 82  : 82 + 22 = 68
3) 68  : 62 + 82 = 100
4) 100 : 12 + 02 + 02 = 1

The solution is 4 because we discovered that the integer 19 is happy after we repeated the process 4 times.

Input:
204

Output:
-1
204 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 –> 42 –> 20 –> 4 –> 16 –> 37 –> 58 –> 89 –> 145 ……

204 is not a happy number because after breaking it several times the results start repeating so we can deduce that if we continue breaking it, the result will never reach 1.

Number of input files is 32.

Don't use pre-calculated values (Don't Cheat)!!!


Added by:Rofael Emil
Date:2010-11-03
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All
Resource:Egyptian Olympiad in Informatics ( EOI ) 2009, August 14 - 21, Cairo

hide comments
2018-10-27 13:09:53
used map to check whether a number was visited before and don't forget to use unsigned long long int
2018-09-16 03:28:18
Wow, my first Floyd's Tortoise and Hare
2018-09-16 02:47:36
AC in std::numeric_limits<unsigned long long>::max() GO!!!
2018-08-25 21:13:38
Time to show off now:
AC in one go without looking at the comments.
2018-08-21 13:05:32
don't trust tool it for this one
2018-08-02 13:08:20
I got a WA after 31 test. Just wonder what I really did wrong. May anybody help to find a mistake? My solution id is 22082540.
2018-06-25 09:42:21
sorry we used pre-calculated value ;)
2018-06-21 10:23:26
when i took number of i/p files=32 i got WA
but upto 32 files gives AC
2018-05-27 06:56:16
My time to really show off!!! xD
AC in one go.
Without any cycle detection code!!
By far, the easiest solution !! :p
2018-05-07 13:48:16
good problem .Tracing 32 nd case is tough for someone.If you give up search for 32nd test case in my blog.

Last edit: 2018-05-07 13:48:30
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.