Check Happy Number in Java

What you’ll learn

  • How to compute sum of squared digits repeatedly.
  • How Floyd cycle detection identifies happy vs unhappy numbers.
  • How to print happy numbers in a range.

Prerequisites

  • Basic Java syntax, loops, conditionals, and methods.
  • Comfort with integer arithmetic and console input/output.

Math definition

This problem is driven by a deterministic numeric rule: for each valid input, apply the same formula repeatedly and classify the result.

Intuition with examples

Work a small input by hand first, then map each step to one Java loop iteration. This makes the control flow and stopping condition clear.

Live preview

Live result
Press "Check happy".

Algorithm

Goal: check whether repeatedly applying digit-square sum reaches 1.

Build sumSquareDigits(n)

Extract each digit with n % 10, square it, and accumulate in sum.

Run Floyd cycle detection

Use slow = f(slow) and fast = f(f(fast)) until both meet; meeting at 1 means happy.

📜 Pseudocode

Pseudocode
function isHappy(n):
    slow = n
    fast = n
    do:
        slow = f(slow)
        fast = f(f(fast))
    while slow != fast
    return slow == 1
1

Single value: 19

java
public class Main {
    static int sumOfSquares(int n) {
        int sum = 0;
        while (n > 0) {
            int digit = n % 10;
            sum += digit * digit;
            n /= 10;
        }
        return sum;
    }

    static boolean isHappy(int n) {
        int slow = n, fast = n;
        do {
            slow = sumOfSquares(slow);
            fast = sumOfSquares(sumOfSquares(fast));
        } while (slow != fast);
        return slow == 1;
    }

    public static void main(String[] args) {
        int number = 19;
        if (number < 1) {
            System.out.println("Use a positive integer.");
            return;
        }
        if (isHappy(number)) {
            System.out.println(number + " is a Happy Number.");
        } else {
            System.out.println(number + " is not a Happy Number.");
        }
    }
}
📤 Output
19 is a Happy Number.
2

Happy numbers in [1, 50]

java
public class Main {
    static int sumOfSquares(int num) {
        int sum = 0;
        while (num > 0) {
            int digit = num % 10;
            sum += digit * digit;
            num /= 10;
        }
        return sum;
    }

    static boolean isHappy(int num) {
        int slow = num, fast = num;
        do {
            slow = sumOfSquares(slow);
            fast = sumOfSquares(sumOfSquares(fast));
        } while (slow != fast);
        return slow == 1;
    }

    public static void main(String[] args) {
        System.out.println("Happy numbers in the range 1 to 50:");
        for (int i = 1; i <= 50; i++) {
            if (isHappy(i)) System.out.print(i + " ");
        }
        System.out.println();
    }
}
📤 Output
Happy numbers in the range 1 to 50:
1 7 10 13 19 23 28 31 32 44 49

Optimization notes

Keep it simple. Prefer clear loops and method extraction before micro-optimizations.

Reuse computed values. Avoid recomputing the same sub-result inside nested loops.

❓ FAQ

Repeatedly replace n by the sum of square of its digits. If it reaches 1, n is happy.
Yes. It stays at 1 immediately.
It detects loops with O(1) extra memory using two pointers moving at different speeds.
This page defines happy numbers for positive integers only.
Happy numbers are usually defined for positive integers, so validate n >= 1.
Each digit-square step is O(digits). Number of Floyd steps is small in practice for int range.

🔄 Input / output examples

Use the sample programs as reference: provide valid numeric input and verify the output pattern matches the problem definition.

nHappy?
1Yes
7Yes
2No
19Yes

Edge cases

Bounds

Smallest valid input

Confirm behavior for minimum accepted values.

Validation

Invalid input

Guard against non-numeric or out-of-range values when input is user-provided.

⏱️ Time and space complexity

MethodTime (per check)Extra space
Floyd cycle detectionO(μ + λ) transitionsO(1)
Visited set approachsame transitionsO(k) orbit size
Range [1, N]O(N) checksO(1) extra per check

Summary

  • Use a direct Java implementation of the numeric rule.
  • Validate input and test boundary cases.
  • Discuss complexity clearly in interviews.
Did you know?

If a positive integer is not happy, iterating digit-square sums always reaches the same unhappy cycle: 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful