Monday, April 29, 2013

Program to check Happy Number


/*Happy Number: A happy number is a number in which the eventual sum of the square
 of the digits of the number is equal to 1.
Example: 23,28
@author : Nitendra Kumar
 */


import java.util.Scanner;

public class Happy
{
  public static int n;
   Happy()  //constructor
   {
       n=0;
    }
    
  public static void main()
  {
      Scanner in=new Scanner(System.in);
      Happy ob=new Happy();
      System.out.println("Enetr a number");
      n=in.nextInt();
      ob.getnum(n);  
      ob.ishappy();
   }

public void getnum(int nn)  
{
 n=nn;
}

public void ishappy() //check if number is Happy Number
{
    int a=n;
    while(a>9)
    {
        a=sum_sq_digits(a);
    }
    if(a==1)
      System.out.println(n+" is a Happy Number");
    else
      System.out.println(n+" is not a Happy Number");
}

public int sum_sq_digits(int x) //recursive function that returns
{                               //sum of square of digits of number x
     if(x==0)
       return 0;
     else   
     {
         int d=x%10;
       return (d*d+sum_sq_digits(x/10));
    }  
 }  

   
/*------------------------Program developed by: Nitendra Kumar------------------------*/      

No comments:

Post a Comment

Ur comments r most welcome...