Math Fundamentals18 sections · 814 units
Open in Course

Happy Number - Hint

Detecting cycles

The tricky part is detecting when you're in a cycle. If you see the same number twice, you're looping and will never reach 11.

Use a set to track all numbers you've seen. Before computing the next sum, check if the current number is already in the set.

To extract digits, use the pattern from earlier: d=nmod10d = n \bmod 10, then n:=n/10n := \lfloor n / 10 \rfloor. Repeat until n=0n = 0.