easyMath & GeometryGoogleFacebook
Happy Number Dance
A puzzler iterates 'sum of squared digits' until the sequence hits 1 (happy) or revisits a value (unhappy loop).
Given n, repeatedly replace n with the sum of the squares of its digits. Return true iff this process reaches 1.
Choose approach
19
0slow
82
1fast
100
21
31/4
Narrationstep 1 of 4
Floyd's cycle detection: slow=19, fast=82 (one step ahead).
Variables
slow=19
fast=82
How to think about it
- Floyd's tortoise/hare also detects the loop in O(1) space.
- Any sequence either hits 1 or enters the (4, 16, 37, ...) cycle.
Edge cases to catch in interview
- n = 1 -> true immediately.
- Powers of 10 -> true (1 after one step).
Examples
Example 1
false{"n":2,"values":[2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed