A happy number is a number that reaches 1 when we keep replacing it with the sum of the squares of its digits. A number that never reaches 1 falls into an endless loop instead, and it is called an unhappy or sad number. To check a happy number in Java, we follow the sequence and stop at 1 or at the first repeated value.
Happy numbers are a popular interview task (LeetCode 202) because the real question behind them is cycle detection, the same problem we solve when a linked list, a redirect chain or a chain of config files loops back on itself.
The following example follows 19 step by step until it reaches 1.
int step1 = 1 * 1 + 9 * 9; // 82
int step2 = 8 * 8 + 2 * 2; // 68
int step3 = 6 * 6 + 8 * 8; // 100
int step4 = 1 * 1 + 0 * 0 + 0 * 0; // 1
We can see that 19 needs four steps, so 19 is happy. We see why every unhappy number gets stuck in the same eight-number loop, and we detect that loop in three ways, with a HashSet, with Floyd’s two-pointer method and with a known-cycle shortcut, before using the same idea on a real redirect table.
1. Happy and Unhappy Numbers
Every start value leads to one of two endings. A happy number reaches 1 and stays there, because 12 = 1. An unhappy number ends up in the cycle 4, 16, 37, 58, 89, 145, 42, 20 and goes around it forever, and no other cycle exists in base 10.

The sequence for 20 shows the cycle. The value 20 goes to 22 + 02 = 4, and from 4 the values run 16, 37, 58, 89, 145, 42 and back to 20.
| Start | Sequence | Result |
|---|---|---|
| 7 | 7, 49, 97, 130, 10, 1 | Happy |
| 32 | 32, 13, 10, 1 | Happy |
| 100 | 100, 1 | Happy |
| 20 | 20, 4, 16, 37, 58, 89, 145, 42, 20, … | Unhappy |
| 2 | 2, 4, 16, 37, … | Unhappy |
The loop always ends, which is the reason any of the following methods terminates. A number with four or more digits drops in size at every step, since even 9999 only gives 4 x 81 = 324. Once the value is below 1000, it stays below 1000, so after at most 1,000 steps some value must repeat.
2. Happy Number Check With a HashSet
All three methods share one helper that computes the next value. It reads digits with % 10 and / 10 and multiplies each digit by itself, so no Math.pow() and no double values are needed.
static int digitSquareSum(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}
The first method remembers every value it has seen in a HashSet. The method add() returns false when the value is already in the set, which means the sequence has started to repeat.
static boolean isHappy(int number) {
if (number < 1) {
return false;
}
Set<Integer> seen = new HashSet<>();
int n = number;
while (n != 1 && seen.add(n)) {
n = digitSquareSum(n);
}
return n == 1;
}
boolean h19 = isHappy(19); // true
boolean h7 = isHappy(7); // true
boolean h28 = isHappy(28); // true
boolean h20 = isHappy(20); // false
boolean h0 = isHappy(0); // false
The guard for numbers below 1 matters. The value 0 maps to 0 forever, and some published solutions that only stop at 1 or 4 loop endlessly for 0. The set version would stop anyway, but returning false early states the rule in code, because happy numbers are positive.
3. Floyd’s Cycle Detection Without a Set
The second method keeps two values instead of a set. The slow value moves one step at a time and the fast value moves two steps, and if the sequence loops, the fast value catches up with the slow one inside the loop. This is the same tortoise-and-hare method used to detect a loop in a linked list.
static boolean isHappyFloyd(int number) {
if (number < 1) {
return false;
}
int slow = number;
int fast = digitSquareSum(number);
while (fast != 1 && slow != fast) {
slow = digitSquareSum(slow);
fast = digitSquareSum(digitSquareSum(fast));
}
return fast == 1;
}
boolean f19 = isHappyFloyd(19); // true
boolean f20 = isHappyFloyd(20); // false
boolean f1 = isHappyFloyd(1); // true
Floyd’s method uses a fixed amount of memory, two int variables, while the set grows with the length of the sequence. The cost is that the fast value computes some steps twice.
4. Stopping at 4 With the Known Cycle
Because every unhappy sequence enters the cycle that contains 4, the third method stops as soon as the value is 1 or 4. It needs no set and no second pointer, but it depends on a fact about base 10 that the code cannot check for itself.
static boolean isHappyShortcut(int number) {
int n = number;
while (n > 1 && n != 4) {
n = digitSquareSum(n);
}
return n == 1;
}
boolean s97 = isHappyShortcut(97); // true
boolean s58 = isHappyShortcut(58); // false
boolean s0 = isHappyShortcut(0); // false
The condition n > 1 also ends the loop for 0 and negative numbers. Use the HashSet or Floyd version when the sequence rule might change, because the shortcut is correct only for the sum of squared digits in base 10.
| Method | Extra memory | Works for other digit rules | Typical use |
|---|---|---|---|
| HashSet of seen values | Grows with the sequence | Yes | Clear code, interviews |
| Floyd’s slow and fast values | Two variables | Yes | Memory-limited code, follow-up questions |
| Stop at 1 or 4 | None | No, base 10 squares only | Bulk checks of many numbers |
5. Listing Happy Numbers and Happy Primes
A stream over a range lists happy numbers with any of the three methods. Combining the happy check with a prime check gives happy primes, numbers that are both happy and prime. The prime check here uses BigInteger.isProbablePrime(), which is reliable for small values.
List<Integer> upTo50 = IntStream.rangeClosed(1, 50).filter(n -> isHappy(n)).boxed().toList(); // [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
long countTo100 = IntStream.rangeClosed(1, 100).filter(n -> isHappyShortcut(n)).count(); // 20
List<Integer> happyPrimes = IntStream.rangeClosed(2, 100).filter(n -> isHappy(n) && BigInteger.valueOf(n).isProbablePrime(20)).boxed().toList(); // [7, 13, 19, 23, 31, 79, 97]
One in five numbers up to 100 is happy. Changing the order of digits or adding zeros keeps the digit squares the same, which is why 13 and 31, or 7 and 70, appear together.
6. Detecting a Redirect Loop in a CMS
The happy-number check is a small version of a problem that appears in production code. Say a CMS stores page redirects as a map from an old path to a new path. An editor adds a redirect from /offers to /deals, while an older entry already sends /deals to /offers. The website follows the chain and the browser shows a “too many redirects” error, so the CMS must reject the new entry when it is saved.
static Optional<String> resolve(Map<String, String> redirects, String path) {
Set<String> visited = new HashSet<>();
String current = path;
while (redirects.containsKey(current)) {
if (!visited.add(current)) {
return Optional.empty(); // loop found
}
current = redirects.get(current);
}
return Optional.of(current);
}
Map<String, String> redirects = Map.of("/sale", "/offers", "/offers", "/deals", "/deals", "/offers");
Optional<String> loop = resolve(redirects, "/sale"); // Optional.empty
Optional<String> fine = resolve(Map.of("/sale", "/offers"), "/sale"); // Optional[/offers]
The resolve() method has the same structure as isHappy(), a set of visited values and a loop that stops at either the final value or a repeat. Returning an Optional lets the save handler show a message to the editor instead of failing on a later request. More beginner programs like this one are listed on the Java examples page.
7. Happy Number FAQs
Once the program works, homework sheets move on to specific numbers such as 7 and 58, and to the word “sad”.
7.1. Why is 7 a happy number?
Because its sequence reaches 1. The values are 7, 49, 97, 130, 10 and 1, since 42 + 92 = 97 and 92 + 72 = 130. The number 7 is the only happy single digit besides 1.
7.2. Is 58 a happy number?
No. The number 58 is part of the unhappy cycle. It goes to 52 + 82 = 89, and the values continue with 145, 42, 20, 4, 16, 37 and 58 again.
7.3. What is a sad number?
A sad number is another name for an unhappy number, a number whose sequence never reaches 1. Both words describe the same set, 2, 3, 4, 5, 6, 8, 9, 11, 12 and so on.
7.4. Is 0 a happy number?
No. The digit-square sum of 0 is 0, so the sequence never reaches 1. Happy numbers are defined for positive integers, and all methods in this article return false for 0.
7.5. Can we solve the happy number problem with recursion?
Yes, by passing the set of seen values to the next call, but the loop is the better choice. A recursive version that only stops at 1 recurses forever for unhappy numbers and ends with a StackOverflowError, while the loop versions in section 2 use no call stack at all.
8. Conclusion
A happy number reaches 1 under the sum of squared digits, and an unhappy number ends in the cycle 4, 16, 37, 58, 89, 145, 42, 20. Since the values drop below 1000 within a few steps, the sequence always repeats or reaches 1, so the check always terminates.
A HashSet of seen values is the clearest check, Floyd’s slow and fast values do the same with two variables, and stopping at 4 is a base-10 shortcut. The same visited-set loop protects real code from redirect and reference cycles.
9. References
- OEIS A007770, Happy numbers
- OEIS A035497, Happy primes
- HashSet.add() Javadoc
- BigInteger.isProbablePrime() Javadoc
Happy Learning !!