Happy numbers

O(n · k)

A happy number repeatedly replaces itself by the sum of the squares of its digits until reaching 1; an unhappy number falls into the cycle 4→16→37→58→89→145→42→20→4. The sequence was popularised by Reg Allenby and studied systematically in the 1990s. This visualiser checks each m in 2..n independently, colouring happy numbers green and unhappy ones tan. Well-known happy numbers include 7, 13, 19, 23, and 28.

Numbers
Edit the input and press Play

How it works

  1. Initialize all numbers as candidates
  2. For each m, iterate digit-square-sum until 1 or cycle
  3. Colour happy numbers green, unhappy numbers tan
  4. Report total happy count

Pseudocode

1isHappy(m):                         # O(k) per number2  seen = {}3  while m != 1 and m not in seen:4    seen.add(m)5    m = sum(d^2 for d in digits(m))6  return m == 178happyNumbers(n):9  for m = 2 to n:10    label[m] = "happy" if isHappy(m) else "unhappy"