

1 #include <set>
2 using namespace std;
3
4 class SquareDigits
5 {
6 private:
7 int s(int x);
8
9 public:
10 int smallestResult(int n);
11 };
12
13 int SquareDigits::s(int x)
14 {
15 int count = 0;
16 while(x >= 10)
17 {
18 int a = x % 10;
19 count += a * a;
20 x = x / 10;
21 }
22
23 if(x < 10)
24 {
25 count += x * x;
26 }
27
28 return count;
29 }
30
31 int SquareDigits::smallestResult(int n)
32 {
33 set<int> se;
34
35 for(int i=0; ;i++)
36 {
37 int k = i;
38 se.clear();
39 while(1)
40 {
41 k = s(k);
42 if(se.find(k) != se.end())
43 {
44 break;
45 }
46 se.insert(k);
47 if(k == n)
48 {
49 break;
50 }
51 }
52
53 if(k == n && se.find(k) != se.end())
54 {
55 return i;
56 }
57 }
58 }
2 using namespace std;
3
4 class SquareDigits
5 {
6 private:
7 int s(int x);
8
9 public:
10 int smallestResult(int n);
11 };
12
13 int SquareDigits::s(int x)
14 {
15 int count = 0;
16 while(x >= 10)
17 {
18 int a = x % 10;
19 count += a * a;
20 x = x / 10;
21 }
22
23 if(x < 10)
24 {
25 count += x * x;
26 }
27
28 return count;
29 }
30
31 int SquareDigits::smallestResult(int n)
32 {
33 set<int> se;
34
35 for(int i=0; ;i++)
36 {
37 int k = i;
38 se.clear();
39 while(1)
40 {
41 k = s(k);
42 if(se.find(k) != se.end())
43 {
44 break;
45 }
46 se.insert(k);
47 if(k == n)
48 {
49 break;
50 }
51 }
52
53 if(k == n && se.find(k) != se.end())
54 {
55 return i;
56 }
57 }
58 }