Does the digit-square chain reach 1?
Start from n and keep replacing the number with the sum of the squares of its digits. For example 23 becomes 2 * 2 + 3 * 3 = 13.
Return true if this reaches 1, and false if it goes round in a loop that never reaches 1.
- Input
n = 7- Output
true
7, 49, 97, 130, 10, 1.
- Input
n = 4- Output
false
4, 16, 37, 58, 89, 145, 42, 20 and then 4 again, so it loops without reaching 1.
Limits
1 <= n <= 2147483647
Hints
Hint 1
The numbers soon become small, so if 1 never comes, some number must come round again.
Hint 2
Keep a set of the numbers seen, or run a slow and a fast copy of the chain until they meet.
Where this was reported
- Zoho, SDE campus interview, 2025 (Medium)
Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.
Run your code to check it on the examples. Submit runs every hidden test.