Write a program to accept a number and check whether it is a happy number or not.

A happy number is a number in which the eventual sum of the square of the digits of the number is equal to 1.

for example:

28–>2^2+8^2=4+64=68

68–>6^2+8^2=36+64=100

100–>1^2+0^2+0^2=1+0+0=1

so 28 is a happy number.

import java.io.*;
class Happy
{
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter a number");
        int num=Integer.parseInt(br.readLine());
        int sum=0;
        double a=0;
        while(num>=0)
        {
            a=num%10;
            a=Math.pow(a,2);
            sum+=a;
            num=num/10;
            if(num==0)
            {
                if(sum<10)
                    break;
                else
                {
                    num=sum;
                    sum=0;
                    continue;
                }
            }
        }
        if(sum==1)
            System.out.println("It is a happy number");
        else
            System.out.println("It is a happy number"); 
    }
}

LEAVE A REPLY

Please enter your comment!
Please enter your name here