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?
[toc]

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,

4x4 = 16

1x1+6x6 = 37

3x3+7x7 = 58

5x5+8x8 = 89

8x8+9x9 = 145

1x1+4x4+5x5 = 42

4x4+2x2 = 20

2x2+0x0 = 4 // Number itself

4 = 16  // Repeating process (loop), see step 1

Example

Here is complete example to find Happy number in java.

import java.util.HashSet;
import java.util.Set;

public class Main
{
    public static void main(String args[]) 
    {
        int number  = 1111111;
        int sum = 0;
        Set numbers = new HashSet();
        while(numbers.add(number)){     
            sum = 0;
            while(number>0) {
                sum += (number % 10)*(number % 10); 
                number /=10;
            }
            number = sum;
        }

        // if sum = 1, it is happy number 
        if(sum == 1) {
            System.out.println("It is a happy number");
        }else {
            System.out.println("It is not a happy number");
        }
    }
}

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.

package org.arpit.java2blog;

public class HappyNumberSlowFast {
    static int getSumOfSquareOfDigit(int num) {
        int ss = 0;
        while (num != 0) {
            ss += (num % 10) * (num % 10);
            num /= 10;
        }
        return ss;
    }

    // method return true if n is Happy number
    static boolean isHappynumber(int num) {
        int slow, fast;

        // initialize slow and fast by num
        slow = fast = num;
        do {
            // move slow number by one step
            slow = getSumOfSquareOfDigit(slow);

            // move fast number by two steps
            fast = getSumOfSquareOfDigit(getSumOfSquareOfDigit(fast));

        } while (slow != fast);

        // If slow and fast point meet and slow is equals to 1,
        // then it is happy number
        return (slow == 1);
    }

    // Main method
    public static void main(String[] args) {
        int n = 1111111;
        if (isHappynumber(n))
            System.out.println(n + " is a Happy number");
        else
            System.out.println(n + " is not a Happy number");
    }

}

Output

1111111 is a happy number

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

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.