CodeArchon

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
0
slow
82
1
fast
100
2
1
3
1/4
Narrationstep 1 of 4

Floyd's cycle detection: slow=19, fast=82 (one step ahead).

1def isHappy(n):
2 def sq(x):
3 s = 0
4 while x: s += (x%10)**2; x //= 10
5 return s
6 slow, fast = n, sq(n)
7 while fast != 1 and slow != fast:
8 slow = sq(slow); fast = sq(sq(fast))
9 return fast == 1
Variables
slow=19
fast=82

How to think about it

  1. Floyd's tortoise/hare also detects the loop in O(1) space.
  2. 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 1false
{"n":2,"values":[2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed