Friday, October 11, 2024

Happy Numbers in Java | What is Happy and Unhappy number? Example of Happy number and Java code for Happy number

Question:

What is a happy number, and how can we determine if a given number is happy in Java?

Understanding Happy Numbers

A happy number is a positive integer that, when repeatedly replaced by the sum of the squares of its digits, eventually reaches 1. If it doesn't reach 1 after an infinite number of iterations, it is considered an unhappy number.

Example of a Happy Number:

 * Start with 19.

 * 1² + 9² = 82

 * 8² + 2² = 68

 * 6² + 8² = 100

 * 1² + 0² + 0² = 1

Since the number eventually reaches 1, 19 is a happy number.

Example of an Unhappy Number:

 * Start with 4.

 * 4² = 16

 * 1² + 6² = 37

 * 3² + 7² = 58

 * 5² + 8² = 89

 * 8² + 9² = 145

 * 1² + 4² + 5² = 42

 * ...

The pattern continues indefinitely without reaching 1, making 4 an unhappy number.

Java Program to Determine Happy Numbers

import java.util.HashSet;


public class HappyNumber {

    public static boolean isHappy(int n) {

        HashSet<Integer> seen = new HashSet<>();


        while (n != 1) {

            int sum = 0;

            while (n > 0) {

                int digit = n % 10;

                sum += digit * digit;

                n /= 10;

            }

            n = sum;


            if (seen.contains(n)) {

                return false; // Found a cycle, not a happy number

            }

            seen.add(n);

        }


        return true; // Reached 1, it's a happy number

    }


    public static void main(String[] args) {

        int number = 19;

        if (isHappy(number)) {

            System.out.println(number + " is a happy number.");

        } else {

            System.out.println(number + " is not a happy number.");

        }

    }

}


Explanation:

 * HashSet: We use a HashSet to keep track of the numbers encountered during the iteration. If a number is encountered again, it indicates a cycle and the number is not happy.

 * Sum of Squares: The while loop calculates the sum of the squares of the digits of the current number.

 * Cycle Detection: If the calculated sum is already in the HashSet, it means a cycle has been detected, and the number is not happy.

 * Checking for 1: If the sum reaches 1, it means the number is happy.

This program efficiently determines if a given number is happy by avoiding infinite loops and using a HashSet for cycle detection.


This Content Sponsored by Genreviews.Online

Genreviews.online is One of the Review Portal Site

Website Link: https://genreviews.online/

Sponsor Content: #genreviews.online, #genreviews, #productreviews, #bestreviews, #reviewportal

 

 


No comments:

Post a Comment