Tuesday, May 3, 2011

10591 - Happy Number


#include<stdio.h>
#define M 2000
bool cycle[M];
long next(long n);
int main()
{
    long m,n,i,j,t;
    //freopen("in.txt","r",stdin);
    scanf("%ld",&t);
    for(i=1;i<=t;i++)
    {
        for(j=0;j<M;j++)cycle[j]=false;
        scanf("%ld",&n);
        m=n;
        if(n>=M)n=next(n);
        while(!cycle[n]&&(n^1))
        {
            cycle[n]=true;
            n=next(n);
        }
        if(n^1)printf("Case #%ld: %ld is an Unhappy number.\n",i,m);
        else printf("Case #%ld: %ld is a Happy number.\n",i,m);
    }
    return 0;
}
long next(long n)
{
    long d,s=0;
    while(n)
    {
        d=n%10;
        d=d*d;
        n=n/10;
        s=s+d;
    }
    return s;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.