Java Unhappy Number Program

Beginner
6 min read
Updated: Nov 2026
2 programs
Live preview

What Is an Unhappy Number?

A positive integer is an unhappy number if repeatedly replacing it with the sum of the squares of its digits never reaches 1. Instead the chain falls into a loop. It is the complement of a happy number.

Remember
n is unhappy  ⇔  digit-square chain never reaches 1

Every unhappy chain ends in this cycle:
  4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4

Example: 2
  2² = 4
  4² = 16
  1² + 6² = 37   ... and so on, back to 4
nChain (short)Result
22 → 4 → 16 → … (cycle)Unhappy
4already in the cycleUnhappy
2020 → 4 → (cycle)Unhappy
1919 → 82 → 68 → 100 → 1Happy

How to Check an Unhappy Number in Java

Reuse the happy-number helper, then flip the answer. Pick a visited set or the stop-at-4 shortcut.

  1. Require n > 0 (positive integers only).
  2. Define f(n) = sum of squares of the digits of n.
  3. Keep applying f until you reach 1 (happy) or detect a loop (unhappy).
  4. Report unhappy when the chain never reaches 1.
MethodIdeaExtra spaceBest for
Visited setUnhappy when a value repeats before 1O(k)Clarity, first solution
Stop at 4Unhappy when the chain hits 4 (known cycle)O(1)Short code, interviews

Pseudocode

Pseudocode
function SumOfSquares(n):
    total = 0
    while n > 0:
        d = n mod 10
        total = total + d * d
        n = n / 10
    return total

function IsUnhappy(n):
    if n <= 0:
        return false

    while n != 1 and n != 4:
        n = SumOfSquares(n)

    return n == 4

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
Core steptotal += (n % 10) * (n % 10); n /= 10
Unhappy whenChain never reaches 1
ComplementHappy number (chain reaches 1)
Known cycle4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
ShortcutStop when n == 1 (happy) or n == 4 (unhappy)
Unhappy up to 202, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16, 17, 18, 20
Happy up to 201, 7, 10, 13, 19

Live Preview

Enter a positive integer to see the digit-square chain and the happy/unhappy verdict.

Positive whole numbers only. Tap a chip or type a value.

Result
n = 2
Chain: 2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4
Verdict: UNHAPPY NUMBER

Worked Walkthrough — n = 2

Square each digit, sum, and replace until a value repeats.

Calculation
Step 1: 2²      = 4
Step 2: 4²      = 16
Step 3: 1² + 6² = 1 + 36  = 37
Step 4: 3² + 7² = 9 + 49  = 58
Step 5: 5² + 8² = 25 + 64 = 89
Step 6: 8² + 9² = 64 + 81 = 145
Step 7: 1² + 4² + 5² = 1 + 16 + 25 = 42
Step 8: 4² + 2² = 16 + 4  = 20
Step 9: 2² + 0² = 4       ← seen before

4 repeats and 1 never appears → 2 is unhappy

Java Programs

Start with a visited set so the stop condition is obvious. Then use the stop-at-4 shortcut and list unhappy numbers in a range.

Example 1 — Visited HashSet

Store every value you produce. Reach 1 → happy; see a repeat first → unhappy.

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

public class UnhappyNumber {
    static int sumOfSquares(int n) {
        int total = 0;
        while (n > 0) {
            int d = n % 10;
            total += d * d;
            n /= 10;
        }
        return total;
    }

    static boolean isUnhappy(int n) {
        if (n <= 0) {
            return false;
        }

        Set<Integer> seen = new HashSet<>();
        while (n != 1 && !seen.contains(n)) {
            seen.add(n);
            n = sumOfSquares(n);
        }
        return n != 1;
    }

    public static void main(String[] args) {
        int number = 2;
        if (isUnhappy(number)) {
            System.out.println(number + " is an Unhappy Number.");
        } else {
            System.out.println(number + " is not an Unhappy Number.");
        }
    }
}

How It Works

  1. sumOfSquares peels digits with % 10 and adds each square.
  2. Reject n <= 0 so only positive integers are checked.
  3. While n is not 1 and has not been seen, add it to seen and replace it with sumOfSquares(n).
  4. The loop ends either at 1 (happy) or on a repeated value (a cycle).
  5. Return n != 1: leaving the loop without reaching 1 means the number is unhappy.

Example 2 — Stop at 4 and List a Range

Every unhappy chain reaches 4, so you can stop there without a set. Then print the unhappy numbers from 1 to 20.

Java
public class UnhappyRange {
    static int sumOfSquares(int n) {
        int total = 0;
        while (n > 0) {
            int d = n % 10;
            total += d * d;
            n /= 10;
        }
        return total;
    }

    static boolean isUnhappy(int n) {
        if (n <= 0) {
            return false;
        }

        while (n != 1 && n != 4) {
            n = sumOfSquares(n);
        }
        return n == 4;
    }

    public static void main(String[] args) {
        System.out.println("Unhappy numbers from 1 to 20:");
        for (int i = 1; i <= 20; i++) {
            if (isUnhappy(i)) {
                System.out.print(i + " ");
            }
        }
    }
}

How It Works

  1. The same sumOfSquares helper drives the chain.
  2. The loop stops at 1 (happy) or 4 (the doorway into the unhappy cycle).
  3. Returning n == 4 is true only for unhappy numbers.
  4. main loops i from 1 to 20 and prints each unhappy value.
  5. The missing values (1, 7, 10, 13, 19) are the happy numbers in that range.

Edge Cases & Pitfalls

Check these before calling the solution done.

1

Not unhappy

1 is happy, so it must return false for an unhappy check.

Cycle

Must stop

Without a visited set or a stop-at-4 rule, unhappy inputs loop forever.

0 / negatives

Out of scope

The definition covers positive integers. Reject the rest instead of calling them unhappy.

Squares

Not digit sum

You square each digit. A plain digit sum is a different problem.

Time and Space Complexity

ProgramTimeExtra space
Visited HashSetO(k · log n)O(k)
Stop at 4O(k · log n)O(1)

Each square-sum step costs O(digits). Values shrink quickly into a small range, so k (chain length until 1 or the cycle) stays small in practice.

Key Takeaways

  • Definition: the digit-square chain never reaches 1 → unhappy.
  • Cycle: unhappy chains end in 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4.
  • Shortcut: loop until n == 1 or n == 4; return n == 4.
  • Test set: 2, 3, 4, 20 unhappy; 1, 7, 19 happy.

One line: sum digit squares — if you land in the 4-cycle instead of 1, the number is unhappy.

Frequently Asked Questions

A positive integer is unhappy if repeatedly replacing it with the sum of the squares of its digits never reaches 1. The chain loops forever instead.
Every unhappy number eventually enters the cycle 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4. That is why spotting a 4 is enough to call a number unhappy.
No. 1 is happy because it already equals 1. Unhappy numbers never reach 1.
4 belongs to the only cycle that unhappy numbers can enter, so once the chain hits 4 it is guaranteed never to reach 1. This avoids storing every visited value.
They are complements. Happy numbers reach 1; unhappy numbers do not. You can reuse the same digit-square helper and flip the final answer.
The usual definition uses positive integers. Reject nonpositive inputs, and do not report them as unhappy.

Next: Harshad Number

Check whether a number is divisible by the sum of its digits.

Harshad number tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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