DSA Tracker

Visualize

Happy Number

Sum of squared digits, repeated until 1 (or a cycle)

time O(log n)space O(log n)

Repeatedly replacing a number with the sum of the squares of its digits either eventually lands on 1 (happy) or falls into a repeating cycle that never reaches 1 (unhappy). Following the chain from 19 shows which one happens here.

Details

Animated on: n = 19 — determine whether n is a happy number.

Problem:Happy NumberEasy

Sum of squared digits, repeated until 1 (or a cycle)

step 1 / 10

19
[0]

Repeatedly replace n with the sum of the squares of its digits. If it ever reaches 1, n is happy.

  • n=0· arr[0] = 19
Pseudocode
1FUNCTION isHappy(n):
2 make an empty set of numbers already seen
3 WHILE n is not 1 and n is not already in the seen set:
4 add n to the seen set
5 n = sum of the squares of n's digits
6 RETURN true if n equals 1, otherwise false

← / → step · space play · Home restart

Every step in words

Show all 10 steps
  1. Repeatedly replace n with the sum of the squares of its digits. If it ever reaches 1, n is happy.
  2. 19 has digits 1 and 9.
  3. 1^2 + 9^2 = 1 + 81 = 82.
  4. 82 has digits 8 and 2.
  5. 8^2 + 2^2 = 64 + 4 = 68.
  6. 68 has digits 6 and 8.
  7. 6^2 + 8^2 = 36 + 64 = 100.
  8. 100 has digits 1, 0, 0.
  9. 1^2 + 0^2 + 0^2 = 1 + 0 + 0 = 1 — we reached 1!
  10. Reaching 1 means the chain terminates happily from here → 19 is a happy number, true.

Now solve it yourself

Watching is the first half. The second is writing it without the animation.