## Sum Square Digits Sequence

### April 27, 2018

Regular readers of this blog know of my affinity for recreational mathematics, and today’s exercise is an example of that.

We looked at happy numbers in a previous exercise. Recently, Fermat’s Library re-published a proof by Arthur Porges, first published in the American Mathematical Monthly in 1945, that the trajectory of the sequence of summing the squares of the digits of a number always ends in 1 (a Happy Number) or a set of eight digits 4, 16, 37, 58, 89, 145, 42, 20 (a Sad Number). So, we look at this task again:

You are given a positive integer. Split the number into its base-ten digits, square each digit, and sum the squares. Repeat until you reach 1 (a Happy Number) or enter a loop (a Sad Number). Return the sequence thus generated.

For instance, 19 is a happy number, with sequence 19, 82, 68, 100, 1, while 18 is a sad number, with sequence 18, 65, 61, 37, 58, 89, 145, 42, 20, 4, 16, 37, …

Your task is to compute the sequence described above for a given *n*. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Although the problem is ill-defined (there is a case of a number being neutral, i.e. neither happy or sad), we’ll look at the case where the number is happy if and only if the end result is 1. Here is my take with Julia.

global sad = [4, 16, 37, 58, 89, 145, 42, 20];

function DigitsOf(n::Int64)

digits = split(string(n), “”)

z = length(digits)

Z = Array{Int64}(z)

end

function IsHappy(n::Int64)

D, nd = DigitsOf(n)

S = [n]

end

Whatever the case, creative problems like this can make someone quite happy, for sure. Happy weekend everyone!

Perl6 solution with a simple loop:

Here is my Golang solution, with a disclaimer that I’m just learning Go and so far don’t like it very much:

Here is a pastebin of the above code (thought WordPress formatted Go these days).

Here’s a Haskell solution. (I’m calling the sequence a “Porges sequence”.)

Python 3 version, one function to generate the sequence, terminating with either a known sad number or 1, and one function to check the ‘happiness’ of a number:

I used mathematical operations to find the sum of squared digits, rather than casting to string, although Python does make that easy :)

Here’s a solution in C.

Example Usage:

@Zach, the problem mentions and links to a proof that all natural numbers are either “happy” or “sad”. I think this contradicts there being any “neutral” numbers.

Zach -> Zack