UVA 10591: Happy Number -solution

#include<bits/stdc++.h>
using namespace std;

int happy(int n)
{
    int temp=n;
    bool visit[10000];
    memset(visit,false,10000);
    while (1)
    {
        int temp2=0;
        while (temp)
        {
        int a=temp%10;
        temp2+=a*a;
        temp/=10;
        }
        if (temp2==1) return 1;
        if (temp2==n) return 0;
        if (visit[temp2]) return 0;
        visit[temp2]=true;
        temp=temp2;
    }
}

int main()
{
    int t,c=1;
    scanf("%d",&t);
    while (t--)
    {
        int n;
        scanf("%d",&n);
        if (happy(n)) printf("Case #%d: %d is a Happy number.\n",c++,n);
        else printf("Case #%d: %d is an Unhappy number.\n",c++,n);
    }
    return 0;
}

Comments

Popular posts from this blog

Codeforces 698A - Vacations

UVA 11364: Parking -Solution

UVA 10550 - Combination Lock : Solution