Happy Number(找规律)

[提交] [状态] [讨论版] [命题人:admin]

题目描述

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 12 + 92 = 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 f to 19 results in:
f(19) = 12 + 92 = 82
f(82) = 82 + 22 = 68
f(68) = 62 + 82 = 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.

输入

Your program is to read from standard input. The input consists of a single line that contains an integer, n (1 ≤ n ≤ 1,000,000,000)

输出

Your program is to write to standard output. Print exactly one line. If the given number n is a happy number, print out HAPPY; otherwise, print out UNHAPPY.

样例输入

19

样例输出

HAPPY

题意:对于题目中给定的数 n ,可以进行对n的每位数字取平方和,可以不断的进行该项操作,

如果在操作的过程中其平方和为1 ,n就是一个HAPPY NUMBER; 否则会是不会出现1 的循环节的情况

,判断该数字n是否是一个HAPPY NUMBER;

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long int
int main()
{	
	ll panduan;
	scanf("%lld",&panduan);
	while(1){
		int x=panduan;
		int sum=0;
		while(x){
			int temp=x%10;
			sum+=temp*temp;
			x/=10;
		}
		panduan=sum;
		if(sum<10)
			break;
	}
	
	if(panduan!=1)
		printf("UNHAPPY\n");
	else
		printf("HAPPY\n");
	
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/dong_qian/article/details/82940491