原题:
Let the sum of the square of the digits of a positive integer S 0 be represented by S 1 . In a similar way, let the sum of the squares of the digits of S 1 be represented by S 2 and so on. If S i = 1 for some i ≥ 1, then the original integer S 0 is said to be Happy number. A number, which is not happy, is called Unhappy number. For example 7 is a Happy number since 7 → 49 → 97 → 130 → 10 → 1 and 4 is an Unhappy number since 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
Input
The input consists of several test cases, the number of which you are given in the first line of the input.
Each test case consists of one line containing a single positive integer N smaller than 10 9 .
Output
For each test case, you must print one of the following messages:
Case #p: N is a Happy number.
Case #p: N is an Unhappy number.
Here p stands for the case number (starting from 1). You should print the first message if the number N is a happy number. Otherwise, print the second line.
Sample Input
3
7
4
13
Sample Output
Case #1: 7 is a Happy number.
Case #2: 4 is an Unhappy number.
Case #3: 13 is a Happy number.
中文:
给你一个数,如果不断计算这个数所有位数的平方和来代替这个数,如果这个数曾经出现过就是一个不快乐数,如果这个数最后变成1就是一个快乐数。
#include<bits/stdc++.h>
using namespace std;
unordered_set<long> us;
long fun(long x)
{
long tmp=0;
while(x!=0)
{
long res=x%10;
tmp+=res*res;
x/=10;
}
return tmp;
}
int main()
{
ios::sync_with_stdio(false);
int t,k=1;
cin>>t;
while(t--)
{
us.clear();
long x;
cin>>x;
long ans=x;
us.insert(ans);
while(true)
{
if(ans==1)
{
cout<<"Case #"<<k++<<": "<<x<<" is a Happy number."<<endl;
break;
}
ans=fun(ans);
if(us.find(ans)!=us.end())
{
cout<<"Case #"<<k++<<": "<<x<<" is an Unhappy number."<<endl;
break;
}
us.insert(ans);
}
}
return 0;
}
解答:
很简单的一道题,可以用stl记录出现过的数即可