Subscribe Us

Happy Number In Java

Happy Number In Java


Java Program To Check Happy number or Not

In Number Theory, A Happy Number is a Number Which
Eventually reaches 1 when replaced by the sum of the square of each digit.

Example :
Given Number : 13
13 is a Happy Number
Because
13 = ( 1*1 )+( 3*3 ) = 1 + 9 = 10
10 = ( 1*1 )+( 0*0 ) = 1 + 0 = 1

Given Number : 28
28 is a Happy Number
Because
28 = ( 2*2 ) +( 8*8 ) = 4 + 64 = 68
68 = ( 6*6 ) +( 8*8 ) = 36+ 64 = 100
100= ( 1*1)+( 0*0 )+ ( 0*0) = 1 + 0 + 0 = 1

Algorithm to check if a number is a Happy Number or Not in Java
you can use the following algorithm:
  1. Read the input number.
  2. Initialize a variable sum to 0.
  3. Create a copy of the input number.
  4. While num is not equal to 0, perform the following steps:
    • Get the last digit of the num by using the modulo operator (%).
    • Square the last digit and add it to sum.
    • Divide the num by 10 to remove the last digit.
    • if num = 0 and sum>=10
      • Reset num to sum and sum to 0.
  5. Check if the sum of the number is equal to 1.
    • If it is 1, the number is a Happy Number.
    • If it is Not 1, the number is Not a Happy Number.

Please note that this implementation assumes that the input number is a positive integer. You may need to add additional checks for negative numbers or other cases depending on your requirements.

Here is an example implementation in Java

Source Code

//Java Program to Check Happy Number Or Not ?
import java.util.*;
public class HappyNumber
 {
  public static void main(String args[])
   {
     Scanner in=new Scanner(System.in);
     int num ,Rd,sum=0;
     System.out.print("Enter a Number To Check : ");
     num=in.nextInt();
     while(num!=0)
      {
        Rd = num % 10 ;
        sum= sum + Rd * Rd ;
        num= num / 10 ;
        if(num==0 && sum>=10)
          {
            num=sum;
            sum=0;
          }
      }
     if(sum==1)
      System.out.print("It is a Happy Number . ");
     else
      System.out.print("It is Not a Happy Number . ");
   }
 }

Output

Sample Input :
Enter a Number To Check : 28
Sample Output:
It is a Happy Number

Sample Input :
Enter a Number To Check : 13
Sample Output:
It is Not a Happy Number

Sample Input :
Enter a Number To Check : 12
Sample Output:
It is Not a Happy Number

Looping Related Programs