UVALive8091 Happy Number【数学】

Consider the following function f defined for any natural number n:

f(n) is the number obtained by summing up the squares of the digits of n in decimal (or base-ten).

  If n = 19, for example, then f(19) = 82 because 1^2 + 9^2 = 82.

  Repeatedly applying this function f, some natural numbers eventually become 1. Such numbers are called happy numbers. For example, 19 is a happy number, because repeatedly applying function to 19 results in:

  f(19) = 1^2 + 9^2 = 82

  f(82) = 8^2 + 2^2 = 68

  f(68) = 6^2 + 8^2 = 100

  f(100) = 12 + 02 + 02 = 1

  However, not all natural numbers are happy. You could try 5 and you will see that 5 is not a happy number. If n is not a happy number, it has been proved by mathematicians that repeatedly applying function f to n reaches the following cycle:

4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.

  Write a program that decides if a given natural number n is a happy number or not.

Input

The input file contains several test cases, each of them consists of a single line that contains an integer, n (1 ≤ n ≤ 1, 000, 000, 000)

Output

For each test case, print exactly one line. If the given number n is a happy number, print out ‘HAPPY’; otherwise, print out ‘UNHAPPY’.

Sample Input

19

5

Sample Output

HAPPY

UNHAPPY


Regionals 2017 >> Asia - Daejeon


问题链接UVA10591 Happy Number

问题简述:(略)

问题分析

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

程序说明

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

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


题记:(略)


参考链接UVA944 Happy Numbers【数学】


AC的C++语言程序如下:

/* UVALive8091 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 n;

    while(~scanf("%d", &n))
        printf("%s\n", ishn(n) ? "HAPPY" : "UNHAPPY");

    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值