Happy and Sad Numbers

From [wu : riddles]

Consider the following process:

  1. Pick a positive integer.
  2. Square each of digits and add the squares together, to get a new number.
  3. Repeat steps 2-3 with the new number.

“Happy numbers” are numbers destined to reduce to one. “Sad numbers” are those that get stuck in an infinite loop of distinct numbers; for example, the loop { 89, 145, 42, 20, 4, 16, 37, 58, 89, 145, ... }.

In general, what kinds of numbers are happy, and what kinds are sad? Give a closed-form expression for which integers are happy, and which integers are sad.