Core Java

Happy / Sad Number Test In Java

When it comes to programming in Java, happy / sad number test is an interesting challenge. Happy numbers are those that, when the sum of the squares of their digits is repeatedly calculated, eventually reach 1. Conversely, sad numbers do not reach 1 and may result in a cycle of numbers that does not include 1. Testing for happiness or sadness involves iterating through this process and determining whether the number meets the criteria. Let us delve into testing happy and sad numbers in Java.

1. Introduction

Happy Numbers is a special set of positive integers that exhibit a particular behavior when operated upon mathematically. This behavior is characterized by a sequence of steps that ultimately leads to the number 1.

1.1 How do Happy Numbers work?

To determine if a number is happy or not, we follow a simple process:

  • Start with any positive integer.
  • Replace the number with the sum of the squares of its digits.
  • Repeat step 2 until the resulting number becomes 1.
  • If the process ends in 1, the number is considered a Happy Number. Otherwise, it falls into the category of Sad Numbers.

2. Code Example

Below is the Java code to test whether a number is happy or sad.

package com.jcg.example;

public class HappySadNumber {

    // Function to find sum of squares of digits of a number
    static int sumOfSquares(int n) {
        int sum = 0;
        while (n != 0) {
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        return sum;
    }

    // Function to check if a number is happy or sad
    static boolean isHappy(int n) {
        // Keep track of visited numbers to detect cycles
        boolean[] visited = new boolean[1000]; // assuming numbers won't exceed 999

        while (true) {
            // If n is 1, it's a happy number
            if (n == 1)
                return true;

            // If n is visited before, it's a sad number
            if (visited[n])
                return false;

            // Mark n as visited
            visited[n] = true;

            // Calculate the sum of squares of digits
            n = sumOfSquares(n);
        }
    }

    public static void main(String[] args) {
        // Test cases
        int[] numbers = { 19, 7, 18, 10, 2 };

        for (int num : numbers) {
            if (isHappy(num)) {
                System.out.println(num + " is a happy number.");
            } else {
                System.out.println(num + " is a sad number.");
            }
        }
    }
}

2.1 Code Breakdown

This Java code defines a:

  • sumOfSquares function takes an integer n and returns the sum of the squares of its digits.
  • isHappy function checks whether a number is happy or sad. It uses a while loop to repeatedly calculate the sum of squares of digits until the result is 1 (happy) or a cycle is detected (sad).
  • In the main method, we have an array of test numbers. We iterate through each number and print whether it’s happy or sad.

2.2 Code Output

When you run the above Java code, it will produce the following output:

19 is a happy number.
7 is a happy number.
18 is a sad number.
10 is a happy number.
2 is a sad number.

3. Improve the Code Complexity

To improve the time complexity of the isHappy function, we can use a different approach that doesn’t rely on repeatedly calculating the sum of squares of digits until we reach 1 or detect a cycle. One alternative approach is to use Floyd’s Cycle Detection Algorithm, also known as the “tortoise and hare” algorithm.

package com.jcg.example;

public class HappySadNumber {

    // Function to find sum of squares of digits of a number
    static int sumOfSquares(int n) {
        int sum = 0;
        while (n != 0) {
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        return sum;
    }

    // Function to check if a number is happy or sad using Floyd's Cycle Detection Algorithm
    static boolean isHappy(int n) {
        int slow = n;
        int fast = n;
        
        do {
            slow = sumOfSquares(slow);
            fast = sumOfSquares(sumOfSquares(fast));
        } while (slow != fast);
        
        return slow == 1;
    }

    public static void main(String[] args) {
        // Test cases
        int[] numbers = { 19, 7, 18, 10, 2 };

        for (int num : numbers) {
            if (isHappy(num)) {
                System.out.println(num + " is a happy number.");
            } else {
                System.out.println(num + " is a sad number.");
            }
        }
    }
}

3.1 Code Breakdown

This Java code defines a:

  • In the isHappy function, we use two pointers: slow and fast. slow moves one step at a time, while fast moves two steps at a time by calculating the sum of squares of digits.
  • If n is a happy number, eventually slow and fast will meet at 1.
  • If n is not a happy number, eventually slow and fast will meet at some other number, indicating a cycle.
  • By using this approach, we avoid repeatedly calculating the sum of squares of digits, leading to better time complexity.

4. Conclusion

In conclusion, when we test happy and sad numbers in Java, we discover how interesting these math ideas are in programming. We use special methods to figure out if a number is happy or sad. This shows us how math and computer science work together. We learn tricks like adding up the squares of digits or using smart algorithms like Floyd’s Cycle Detection Algorithm. These help us understand how numbers act and make our code run better. Testing these numbers doesn’t just teach us about coding—it also shows us the beauty and complexity of simple math ideas. Plus, it’s a great way to practice solving problems and thinking like a computer scientist.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button