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.


问题链接UVA10591 Happy Number

问题简述:(略)

问题分析

  某一个正整数n,对其各位数字分别平方再求和得到一个新数,重复同样的计算,最终和变成1,则称n为快乐数;如果出现循环变不成1则不是快乐数。

程序说明

  使用set来判重复是一个好做法。

  函数ishn()是CV来的,其中包含统计步数的逻辑,参见参考链接。


题记:(略)


参考链接UVA944 Happy Numbers【数学】


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;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值