easyMath / GeometryPure DSA~13 min
Retry Digit Convergence
A health-check repeatedly squares-and-sums the digits of a status code. Some codes converge to 1 (healthy); others loop forever. Decide whether a given code converges.
Problem
A happy number is defined by repeatedly replacing a number with the sum of the squares of its digits; the number is happy if this process reaches 1. Given n, return true if n is happy, false otherwise (it loops without reaching 1).
Input
A positive integer n (1 ≤ n ≤ 2^31 − 1).
Output
A boolean — true if n is happy.
Constraints
- Unhappy numbers enter a cycle that never includes 1
- Detect the cycle to terminate
Examples
Example 1
Input
n = 19
Output
true
1²+9²=82 → 8²+2²=68 → 6²+8²=100 → 1²+0²+0²=1.
Example 2
Input
n = 2
Output
false
The sequence 2→4→16→37→… cycles without reaching 1.