Java Program to Check Happy Number

Mathematics for Programming Numbers (Article) Numbers (Program)

12

Given Input:

Enter a number to check if it's a Happy Number: 19

Expected Output:

19 is a Happy Number!

Program:

import java.util.HashSet;
import java.util.Scanner;

public class HappyNumberChecker {

    // Function to calculate the sum of squares of digits
    public static int sumOfSquares(int number) {
        int sum = 0, digit;
        while (number > 0) {
            digit = number % 10; // Extract the last digit
            sum += digit * digit; // Add the square of the digit
            number /= 10; // Remove the last digit
        }
        return sum;
    }

    // Function to check if a number is a Happy Number
    public static boolean isHappyNumber(int number) {
        HashSet<Integer> seenNumbers = new HashSet<>();
        
        while (number != 1 && !seenNumbers.contains(number)) {
            seenNumbers.add(number); // Track visited numbers
            number = sumOfSquares(number); // Update the number
        }
        
        return number == 1; // Return true if it reaches 1
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number to check if it's a Happy Number: ");
        int number = scanner.nextInt();

        if (isHappyNumber(number)) {
            System.out.println(number + " is a Happy Number!");
        } else {
            System.out.println(number + " is NOT a Happy Number.");
        }

        scanner.close();
    }
}

Output:

Enter a number to check if it's a Happy Number: 20
20 is NOT a Happy Number.

This Particular section is dedicated to Programs only. If you want learn more about Mathematics for Programming. Then you can visit below links to get more depth on this subject.