After a summer hiatus, it’s time again for the Friday Fragment: our programming-related puzzle.
This Week’s Fragment
During the sabbatical, so many devious ideas came to mind: Sudoku solvers, quines, LOLCODE, you name it. But discretion prevailed; after all, this is about code fragments: small, often elegant solutions that can be written relatively quickly, or used to try new languages and compare their merits. And since this is such a happy day (with a sunny, happy daytime high), we’ll take on happy numbers.
A happy number is a positive integer which you can replace by the sum of the squares of its digits and repeat the process until you get to 1. For example, 7 is a happy number because its series ends at 1: 72 = 49, 42 + 92 = 97, 92 + 72 = 130, 12 + 32 + 02 = 10, 12 + 02 = 1. So:
Write code to compute happy numbers starting at 1. To eventually get your computer back, you can stop at some high limit: whatever makes you happy.
Of course, this is a common math puzzle, so there are likely many implementations on the web. But no peeking. Try it for yourself and aim for something interesting: least amount of code, a new (to you) or unusual language, best use of recursion or induction, best performance, etc.
To “play along”, post the solution as a comment or send it via email. To avoid “spoilers”, simply don’t expand comments for this post.
Last Week’s Fragment?
There wasn’t one! The Friday Fragment was on summer break, and what a break it was! But with the advent of fall, watch this space for new puzzles and solutions.