Monday, May 15, 2017

uva problem 10591 - Happy Number


problem link

Discussion : In this problem  make sum of every digit of number. if until the sum less then 10 or 1. replace n with sum. if sum=1 then number is happy otherwise unhappy.

at first try yourself,if you can't then only see the code.


#include<bits/stdc++.h>
using namespace std;
int main()
{

   long long n,i,r,cnt,d,m,t,k,sum;
   cin >>t;
   for(k=1;k<=t;k++)
   {
      cin >>n;

      m=n;
       sum=0;
       here:
      while(n>0)
      {
         r=n%10;
         n=n/10;
         sum+=r*r;

      }
      if(sum<10)
      {
      cout <<"Case #"<<k<<':'<<' '<<m;
      if(sum==1)
      cout <<" is a Happy number.\n";
      else
      cout <<" is an Unhappy number.\n";
      }
      else
      {
         n=sum;
         sum=0;
         goto here;
      }
   }
return 0;

}

No comments:

Post a Comment