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
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
function isHappy(n):
slow = n
fast = n
do:
slow = f(slow)
fast = f(f(fast))
while slow != fast
return slow == 1Single value: 19
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.");
}
}
}19 is a Happy Number.
Happy numbers in [1, 50]
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();
}
}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
🔄 Input / output examples
Use the sample programs as reference: provide valid numeric input and verify the output pattern matches the problem definition.
| n | Happy? |
|---|---|
1 | Yes |
7 | Yes |
2 | No |
19 | Yes |
Edge cases
Smallest valid input
Confirm behavior for minimum accepted values.
Invalid input
Guard against non-numeric or out-of-range values when input is user-provided.
⏱️ Time and space complexity
| Method | Time (per check) | Extra space |
|---|---|---|
| Floyd cycle detection | O(μ + λ) transitions | O(1) |
| Visited set approach | same transitions | O(k) orbit size |
Range [1, N] | O(N) checks | O(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.
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.
8 people found this page helpful
