-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathHPYNOS.cs
57 lines (49 loc) · 1.35 KB
/
HPYNOS.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System;
using System.Collections;
// https://www.spoj.com/problems/HPYNOS/ #digits #simulation
// Determines if repeatedly adding the squared digits of a number eventually gets to 1.
public static class HPYNOS
{
// n is limited to 2,147,483,647, so by inspection 1,999,999,999 will give us the
// limit of the numbers we can get after at least one breaking. That is:
// 1^2 + 9 * 9^2 = 730. So we'll have a size 731 bool array to keep track of
// what's already seen.
public static int Solve(int n)
{
bool[] numbersAlreadySeen = new bool[731];
int breakCount = 0;
while (n != 1)
{
n = Break(n);
++breakCount;
if (numbersAlreadySeen[n])
{
return -1; // Caught in a cycle that will never terminate.
}
else
{
numbersAlreadySeen[n] = true;
}
}
return breakCount;
}
private static int Break(int n)
{
int result = 0;
while (n != 0)
{
int lastDigit = n % 10;
result += lastDigit * lastDigit;
n /= 10;
}
return result;
}
}
public static class Program
{
private static void Main()
{
Console.WriteLine(
HPYNOS.Solve(int.Parse(Console.ReadLine())));
}
}