Happy Number program in Java

In this article, we are going to learn to find Happy Number using Java. Let’s first understand, what is Happy Number?

What is a Happy Number?

A number which leaves 1 as a result after a sequence of steps and in each step number is replaced by the sum of squares of its digit. For example, if we check whether 23 is a Happy Number, then sequence of steps are

Step 1: 2×2+3×3 = 4+9 = 13 // Sum of square of each digit
Step 2: 1×1+3×3 = 1+9 = 10
Step 3: 1×1+0x0 = 1 (A Happy Number)

We will see two approaches to find happy number in java.

Using Hashset

In this approach, we will use Hashset to tract the cycle and if sum=1 at the end of the cycle, then it is happy number.

Algorithm

  1. Take one variable sum for storing sum of square.
  2. Intialize a HashSet numbers, we will use this HashSet to track repeating cycle.
  3. Iteate through while loop until we get same number again and do following:
    1. Calculate the square of each digit present in the number and add it to the variable sum and divide the number by 10.
    2. Assign sum to number after each iteration
  4. If result sum is equal to 1, then the number is a Happy Number.
  5. Else the number is not happy Number.

Note: A number can not be a Happy Number if it makes a loop in its sequence. For example,

Example

Here is complete example to find Happy number in java.

Output

It is a happy number

Using slow and fast pointers

In this approach, we will use slow and fast pointer to track the cycle.

Algorithm

  1. initialize two variables slow and fast with given number.
  2. Iterate through do while loop until we get a cycle (slow!=fast)
    1. Move slow pointer once by calling getSumOfSquareOfDigit() once.
    2. Move fast pointer twice by calling getSumOfSquareOfDigit() twice.
  3. If slow is equal to 1 at the end of cycle, it means it is happy number.

Example

Here is complete example to find Happy number in java.

Output

1111111 is a happy number

That’s all about How to find Happy Number in Java

Was this post helpful?

Leave a Reply

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