Tuesday, 8 May 2012

UVa 10591 Happy Number Solution

#include<stdio.h>
int main()
{
long long i,j,k,d,sum,num,t,n;
while(scanf("%lld",&t)==1)
{
for(k=1;k<=t;k++)
{
scanf("%lld",&n);
num=n;
for(j=1;j!=0;j++)
    {
    sum=0;
    for(i=1;i!=0;i++)
        {
        d=num%10;
        num=num/10;
        sum=sum+d*d;
        if(num==0)
            {
            num=sum;
            break;
            }
        }
    if(num<=9)
    break;
    }
if(num==1 || num==7)
    printf("Case #%lld: %lld is a Happy number.\n",k,n);
else
    printf("Case #%lld: %lld is an Unhappy number.\n",k,n);
}
}
}

2 comments:

  1. can you explain the code because I cannot understand how did you manage the numbers for 10^9 and its digits. how did you break the digits and count them???

    ReplyDelete
  2. #include
    long long int spilt(long long a)
    {
    long long int sum=0,i,j,res;
    while(a!=0)
    {
    res=a%10;
    sum+=res*res;
    a/=10;
    }
    return sum;
    }
    int main()
    {
    long long int t=1,n=1,d,i,j;
    scanf("%lld",&t);
    for(i=1;i<=t;i++)
    {
    scanf("%lld",&n);
    if(n<10)
    d=n*n;
    else
    d=n;
    while(d>=10)
    {
    d=spilt(d);
    }
    if(d==1)
    printf("Case #%lld: %lld is a Happy number.\n",i,n);
    else
    printf("Case #%lld: %lld is an Unhappy number.\n",i,n);

    }
    return 0;
    }

    ReplyDelete