Happy Number - Programming Example

Programming Example

The examples below apply the 'happy' process described in the definition of happy given at the top of this article, repeatedly; after each time, they check for both halt conditions: reaching 1, and repeating a number. Everything else is book-keeping (for example, the Python example precomputes the squares of all 10 digits).

  • Simple test in Python to check if a number is happy.
SQUARE = dict def is_happy(n): s = set while (n > 1) and (n not in s): s.add(n) n = sum(SQUARE for d in str(n)) return n == 1

Read more about this topic:  Happy Number

Famous quotes containing the word programming:

    If there is a price to pay for the privilege of spending the early years of child rearing in the driver’s seat, it is our reluctance, our inability, to tolerate being demoted to the backseat. Spurred by our success in programming our children during the preschool years, we may find it difficult to forgo in later states the level of control that once afforded us so much satisfaction.
    Melinda M. Marshall (20th century)