1. 程式人生 > >UVA10591 Happy Number【數學】

UVA10591 Happy Number【數學】

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 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.

問題簡述:(略)

問題分析

  某一個正整數n,對其各位數字分別平方再求和得到一個新數,重複同樣的計算,最終和變成1,則稱n為快樂數;如果出現迴圈變不成1則不是快樂數。

程式說明

  使用set來判重複是一個好做法。

  函式ishn()是CV來的,其中包含統計步數的邏輯,參見參考連結。

題記:(略)


AC的C++語言程式如下:

/* UVA10591 Happy Number */

#include <bits/stdc++.h>

using namespace std;

int ishn(int n) {
    set<int> s;
    int step = 1;
    while (n != 1) {
        step++;

        int sum = 0;
        while (n) {
            int d = n % 10;
            sum += d * d;
            n /= 10;
        }
        n = sum;
        if (s.count(n)) break;
        else s.insert(n);
    }
    return n == 1 ? step : 0;
}

int main()
{
    int t, caseno = 0, n;

    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);

        if(ishn(n))
            printf("Case #%d: %d is a Happy number.\n", ++caseno, n);
        else
            printf("Case #%d: %d is an Unhappy number.\n", ++caseno, n);
    }

    return 0;
}