call(back)
Algorithms & Data StructureseasySign in to star problems

Happy Numbers Up to N

A number is happy when repeatedly replacing it by the sum of the squares of its digits reaches 1; every other number falls into a loop that never contains 1. Return every happy number from 1 to n inclusive, in increasing order. Checking each number from scratch repeats the same walks over and over; share the work so that no value's fate is computed twice.

happyNumbersUpTo(50)  ->  [1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49]
happyNumbersUpTo(6)   ->  [1]

Hints

Hint 1

Keep a map from value to happy or not, seeded with 1 → true. Walk a number until the current value is in the map or has already appeared on this walk.

Hint 2

Every value on the walk shares the outcome: a known value passes its answer back along the path; a repeat inside the walk marks the whole path unhappy.

Hint 3

Walks pass through values above n (99 goes to 162); memoise them too, since later walks reuse them.

Topics

Asked at

Similar Problems6