Solution of 10591 - Happy Number

Problem Description
source:https://uva.onlinejudge.org/external/105/10591.html

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 




13

Sample Output 

Case #1: 7 is a Happy number. 
Case #2: 4 is an Unhappy number. 
Case #3: 13 is a Happy number.

Solution:
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include<stdio.h>
#include<stdlib.h>

long int CheckHappy(long int n);
using namespace std;
long int a[1000000],indx;
int main()
{
    long int t, n, i,happy;
    while(scanf("%ld",&t)==1)
    {
        for(i=1;i<=t;i++)
        {
            scanf("%ld",&n);
            if(n==0)
            {
                printf("Case #%d: %ld is an Unhappy number.\n", i, n);
                continue;
            }
            a[0]=n;
            indx=1;
            happy=CheckHappy(n);
            if(happy==1)
                printf("Case #%d: %ld is a Happy number.\n", i, n);
            else
                printf("Case #%d: %ld is an Unhappy number.\n", i, n);
        }
    }
}

long int CheckHappy(long int n)
{
    long int mod, sum=0,set=0,j;
    if(n<10)
        sum=n*n;
    else
    {
        while(n!=0)
        {
            mod=n%10;
            sum=sum+(mod*mod);
            n=n/10;

        }
    }
    a[indx++]=sum;
    for(j=0;j<indx-1;j++)
    {
        if(a[j]==sum)
            set=1;
    }
    if(sum==1 || set==1)
        return (sum);
    else
        return CheckHappy(sum);
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience