首页 > 代码库 > UVA - 10591 Happy Number

UVA - 10591 Happy Number

Happy Number

 UVA - 10591

Let the sum of the square of the digits of a positive integer S0 be represented by S1. In a similar way, let the sum of the squares of the digits of S1 be represented by S2 and so on. If Si = 1 for some i ≥ 1, then the original integer S0 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 109.

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就是happy的,手动试了下,小于10的只有1满足,所以我只要把它平方和到一位数就行了,要不然这个循环走不出来,然后继续循环递归就行了

#include <stdio.h>
int f(int b)
{
    int s=0;
    while(b)
    {
        int t=b%10;
        s+=t*t;
        b/=10;
    }
    if(s<10)return s;
    else return f(s);
}
int main()
{
    int T;
    scanf("%d",&T);
    for(int i=1; i<=T; i++)
    {
        int x;
        scanf("%d",&x);
        printf("Case #%d: %d is a",i,x);
        if(f(x)==1)
            printf(" Happy number.\n");
        else printf("n Unhappy number.\n");

    }
    return 0;
}

 

UVA - 10591 Happy Number