Monday , December 18 2017
Home / Blue J / Java program to check for a happy number

Java program to check for a happy number

This is a java program for happy number but before that what is a happy number.

A number whose sum of the square of digits is ultimatly equal to 1 is a happy number. By ultimately we mean that starting with any positive number we continue the addition of square of digits till we get a single digit number (0 ~ 9). But the on whose sum is ultimately 1 is a happy number.

Java program to check for a happy number

import java.io.*;
class happynumber
{
public static void main(String args[])throws Exception
{
int i,j;
happyno obj=new happyno();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter a number : ");
i=Integer.parseInt(br.readLine());
while((j=obj.happy(i))/10!=0)       //   You have to check the sum of all digits until a single digit is achieved i.e. sum=1,2,3,..9
{
i=j;				// If sum of digits= 19 it then again goes to 1+9 =10 and again 1+0= '1' a single digit to check if 1 or not
}
if ( j==1)
System.out.println("It is a happy number ");
else
System.out.println("Not a happy number");
}

int happy(int n)
{
if(n/10==0)
return n*n;
else
return (int)Math.pow(n%10,2)+ happy(n/10);
}
}

 OUTPUT: 

Program to check it is a happy number
Program to check a happy number

Incoming terms: Java program to check a happy number, program to check for a happy number.

Check Also

Java program to implement polymorphism

Java program to implement polymorphism: Polymorphism is a technique in java with which you can ...

5 comments

  1. /*
    A better program for happy numbers
    */

    import java.util.*;
    public class HAPPY
    {
    public static void happy(String[]args)
    {
    int num,sum=0,a,b;
    Scanner sc = new Scanner(System.in);
    System.out.print(“Enter a number : ” );
    num = sc.nextInt();
    b=num;
    sum=num;
    do{
    num=sum;sum=0;
    do{
    a=num%10;
    sum+=a*a;
    num/=10;
    }while(num>0);
    }while(sum>9);
    if(sum==1)
    System.out.println(b+” is a Happy number”);
    else
    System.out.println(b+” is a sad number “);
    }
    }

  2. //Another approach

    import java.util.*;
    class HN
    {
    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    int n=sc.nextInt();
    int n1=n;
    int sq=0,sq1=0;
    while(n>0)
    {
    int r=n%10;
    sq+=r*r;
    while(sq>9)
    {
    int r1=sq%10;
    sq1+=r1*r1;
    sq=sq/10;
    }
    n=n/10;
    }
    if(sq==1)
    System.out.print(n1+” is a happy number”);
    else
    System.out.print(n1+” is not a happy number”);

    }
    }

  3. can anyone solve it by using for loop

Leave a Reply

Your email address will not be published. Required fields are marked *