Java program to check happy number using recursion

Java program to check happy number using recursion

Write a Java program to check if the given number is happy or not is a commonly asked coding interview question. To solve this problem, first we need to know what is a happy number? Take any positive integer, find the sum of the squares of its digits, repeat this process until you get 1 or if the sum equals 4(i.e repeats the cycle again). If the sum equals 1 (in the process) then the given number is happy otherwise it is an unhappy number (or sad number).

For example 13 is a happy number,

1² + 3² => 1 + 9 => 10

1² + 0² => 1.

16 is not a happy number,

1² + 6² => 1 + 36 => 37

3² + 7² => 9 + 49 => 58

5² + 8² => 25 +64 => 89

8² + 9² => 64 + 81 => 145

1² + 4² + 5² => 1+16+25 => 42

4² + 2² => 16 +4 => 20

2² + 0² => 4 +0 => 4

=> 16 (the cycle repeats again).

The interviewer may also ask you to find if a given number is happy prime number. In this case you need to check if the number is both prime and happy. Check this post for prime number program in Java.

Now we will see Java program to check happy number using recursion.

HappyNumber.java

Below is a sample output of the program.

The program can also be solved in another way in which we use HashSet to check if the cycle repeats again. Below is the Java program for the same.

Here is a sample output of the program.

That’s all about happy number program in Java. Are you happy? Post it in the comments section.

The following two tabs change content below.

Uday

Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.