Happy Number In Java


In this problem section, we are going to create programs to find the happy number in java. We are going to see 3 different approaches to solve the problem.

    Table Of Contents

  1. Introduction To Happy Number
  2. Method 1: Normal approach
  3. Method 2: Using HashSet
  4. Method 3: Double Step
  5. Conclusion

Happy number in java

Introduction To Happy Number

A happy number is a number that is defined by the following process:

Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers.

For example, 19 is a happy number because:

19 => 12 + 92 = 82
82 => 82 + 22 = 68
68 => 62 + 82 = 100
100 => 12 + 02 + 02 = 1

In the above example, the process stops at 1, so the number is a happy number. Whereas 4 is not a happy number because:

4 => 42 = 16
16 => 12 + 62 = 37
37 => 32 + 72 = 58
58 => 52 + 82 = 89
89 => 82 + 92 = 145
145 => 12 + 42 + 52 = 42
42 => 42 + 22 = 20
20 => 22 + 02 = 4

You can see we started with 4 and again we returned to 4, which means we have a cycle. So 4 is not a happy number.

Happy number example
Happy number example

Later in this section, we are going to use the fact that 1 is a happy number and 4 is not a happy number to solve the problem.


Method 1: Normal approach

Let's now start creating Programs in Java to find the happy number.

In this first method, we will use the normal approach. Where we will start with the input number and then keep on summing the squares of the digits until we come to some conclusion.

Here is the code:

import java.util.Scanner;

public class HappyNumber {
  static int isHappy(int n) {
    if (n == 1 || n == 7) return 1;
    if (n == 4) return 0;

    int sum = 0;
    int temp = n;
    while (temp != 0) {
      int digit = temp % 10;
      sum += digit * digit;
      temp /= 10;
    }
    if (sum == 1)
      return 1;
    else if (sum == 4)
      return 0;
    else
      return isHappy(sum);
  }

  public static void main(String[] args) {
    // take number input
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();

    // check if the number is happy
    int isHappy = isHappy(num);
    // print result
    if (isHappy != 0) {
      System.out.println("Yes, " + num + " is a happy number");
    } else {
      System.out.println("No, " + num + " is not a happy number");
    }
    // close scanner
    sc.close();
  }
}

Now, we will run the program and see the output:

$ java HappyNumber
Enter a number: 19
Yes, 19 is a happy number
Enter a number: 4
No, 4 is not a happy number

Code Explanation:

  1. First, take the number input from the user using the Scanner class.
  2. Then, call the isHappy method and pass the number as an argument.
  3. The isHappy method takes the number and if the number is 1 or 7, it returns 1. If the number is 4, it returns 0.
  4. Then execute a while loop that splits the number into digits and squares for each digit. Then, add the squares of the digits and store it in a variable called sum.
  5. If the sum is 1, it means we have come to some conclusion and the number is happy. If the sum is 4, then it is unhappy, if it is some other number, then we will call the isHappy method again and pass the sum as an argument.
  6. Finally, print the result.

Method 2: Using HashSet

There is another approach to find the happy number. Here, we will use a HashSet to store the numbers that we have already seen.

In Java, the HashSet class stores the unique elements in a collection. It is just like set in other languages. It is a collection of elements that do not allow duplicates.

While calculating the sum of the squares of the digits, we will check if the number (square sum) is already present in the HashSet. If it is, then it is not a happy number because this creates a loop in the process. If it is not present, then we will add it to the HashSet and call the squareSum method again with the current sum as an argument.

Here is the program to find the happy number using HashSet:

import java.util.HashSet;
import java.util.Scanner;

public class happyNumber {
  static int digitSquareSum(int n) {
    int sum = 0;
    while (n > 0) {
      sum += (n % 10) * (n % 10);
      n /= 10;
    }
    return sum;
  }

  public static void main(String[] args) {
    // take number input
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();
    HashSet<Integer> set = new HashSet<Integer>();

    int temp = num;
    while (true) {
      temp = digitSquareSum(temp);

      if (temp == 1) {
        System.out.println("Yes, " + num + " is a happy number");
        break;
      }
      if (set.contains(temp) || temp == 4) {
        System.out.println("No, " + num + " is not a happy number");
        break;
      }
    }
    // close scanner
    sc.close();
  }
}

Output:

$ java happyNumber
Enter a number: 19
Yes, 19 is a happy number
Enter a number: 1995
Yes, 1995 is a happy number
Enter a number: 4
No, 4 is not a happy number

Code Explanation:

  1. Take the number input from the user.
  2. Create a HashSet to store the numbers that we have already seen. Also, initialize a 'temp' variable to perform the program operations.
  3. Execute an infinite while loop. Within this loop call the digitSquareSum method and pass the number as an argument.
  4. The digitSquareSum method takes the number and returns the sum of the squares of the digits.
  5. If the sum is 1, it means it is a happy number. If the sum is 4, or if the sum is already present in the HashSet, then it is not a happy number.
  6. If the sum is not 1 or 4, then we will add it to the HashSet and call the digitSquareSum method again with the current sum as an argument.
  7. Finally, print the result.

Method 3: Double Step

Have you ever solved the problem of finding a loop in a linked list?🤔

An approach used to find the loop is the double-step method. Where there are 2 pointers, one moves one step, and the other moves two steps. If there is a loop, then the pointers will meet at the same node.

We can use the same concept here to find a loop in the square sum of the digits. We will use 2 different variables, one will solve the square sum of the number and the other will solve 1 step ahead, the square sum of the square sum of the number.

Here is the program to find the happy number using a double step:

import java.util.Scanner;

public class happyNumber {
  static int digitSquareSum(int n) {
    int sum = 0;
    while (n > 0) {
      sum += (n % 10) * (n % 10);
      n /= 10;
    }
    return sum;
  }

  public static void main(String[] args) {
    // take number input
    Scanner sc = new Scanner(System.in);
    int num = sc.nextInt();

    int slow = num;
    int fast = num;
    while (true) {
      slow = digitSquareSum(slow);
      fast = digitSquareSum(digitSquareSum(fast));
      if (slow == fast) {
        System.out.println("No, " + num + " is not a happy number.");
        break;
      }
      if (slow == 1 || fast == 1) {
        System.out.println("Yes, " + num + " is a happy number.");
        break;
      }
    }
    // close scanner
    sc.close();
  }
}

Output:

$ java happyNumber
Enter a number: 24
No, 19 is not a happy number
Enter a number: 44
Yes, 44 is a happy number

Code Explanation:

  1. Take the number input from the user.
  2. Initialize 2 variables, one will solve the square sum of the number and the other will solve the square sum of the square sum of the number.
  3. Execute an infinite while loop. Within this loop calculate squareSum(num) and squareSum(squareSum(num)).
  4. If the 2 variables are equal, then there is a loop and the number is not a happy number.
  5. If the variables are not equal, then we will check if the square sum of the number is 1. If it is 1, it is a happy number.
  6. Finally, break the loop and print the result.

Conclusion

We have discussed and created 3 programs to find the happy number in Java using different approaches. All the program has a time complexity of O(nlog(n)) and space complexity of O(1) only problem solved using HashSet has a space complexity of O(n).

Jump to the next problems Factorial program using python, Fibonacci series using python, etc.