Visualize

Pattern visualizer

Happy Number

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. Animated on: n = 19 — determine whether n is a happy number..

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

time O(log n)space O(log n)step 1 / 10
19
[0]
line 1

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

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

Where to practice Math