Problem: Write a java program to determine whether a given number is happy or not.

In number theory, a happy number is a number that eventually reaches 1 when replaced by the sum of the square of each digit.

Wikipedia

For example: 7

happy number

Whereas the numbers, whose sum of the square of each digit results in 4 are sad or unhappy numbers.

Because the sequence starting with 4 eventually reaches 4, thus gets stuck into an infinite loop.

Method 1: Using while loop

To check whether a given number is happy or not, we compute the square of each digit of the number until it either results in 1 or 4.

If the sum results into 1, then we output happy number and if the sum results in 4, we output unhappy number.

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter a number");
    int num = in.nextInt();
 
    //Loop until you don't get sum either as 1 or 4
    while(num !=1 && num != 4){
      num = sumOfDigits(num);
    }
 
    if(num == 1)
      System.out.println("Happy number");
    else
      System.out.println("Not a Happy number");
  }
 
  //Function to return sum of square of digits
  private static int sumOfDigits(int num){
    int sum = 0;
    while(num>0){
      sum += Math.pow(num%10, 2);
      num = num/10;
    }
    return sum;
  }
}

Output:

Enter a number
32
Happy number

Method 2: Using Recursion

We can also check happy number in Java using recursion.

In each recursive call, we pass the sum of the square and return true if the value is 1 and if the value 4, we return false.

import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
 
    System.out.println("Enter a number");
    int num = in.nextInt();
 
    if(isHappy(num))
      System.out.println("Happy Number");
    else
      System.out.println("Not a Happy number");
  }
 
  private static boolean isHappy(int num){
    if(num == 1)
      return true;
    if(num == 4)
      return false;
 
    //recall the function with sum value
    return isHappy(sumOfDigits(num));
  }
 
  //Function to return sum of square of digits
  private static int sumOfDigits(int num){
    int sum = 0;
    while(num>0){
      sum += Math.pow(num%10, 2);
      num = num/10;
    }
    return sum;
  }
}

Output:

Enter a number
7
Happy number

In this tutorial, we learned to check happy numbers using the Java programming language.

Leave a Reply