这套题跟2019年考研上机题难度差了几个数量级,建议完成时间不超过80分钟。
7-1 Happy Numbers (20 分)
A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers and the number of iterations is called the degree of happiness, while those that do not end in 1 are unhappy numbers (or sad numbers). (Quoted from Wikipedia)
For example, 19 is happy since we obtain 82 after the first iteration, 68 after the second iteration, 100 after the third iteration, and finally 1. Hence the degree of happiness of 19 is 4.
On the other hand, 29 is sad since we obtain 85, 89, 145, 42, 20, 4, 16, 37, 58, and back to 89, then fall into an endless loop. In this case, 89 is the first loop number for 29.
Now your job is to tell if any given number is happy or not.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N lines follow, each contains a positive integer (no more than 104) to be tested.
Output Specification:
For each given number, output in a line its degree of happiness if it is happy, or the first loop number if it is sad.
Sample Input:
3
19
29
1
Sample Output:
4
89
0
#include<cstdio>
#include<cmath>
#include<set>
using namespace std;
int getNext(int a)
{
int ans=0;
do{
ans+=pow(a%10,2);
a/=10;
}while(a!=0);
return ans;
}
int main()
{
int n,a;
scanf("%d",&n);
for(