Sum Square Digits Sequence
April 27, 2018
Here is our solution, with help from the Standard Prelude; we short-circuit the loop by stopping as soon as any member of the loop is found:
(define (ssds n) ; sum square digits sequence (let loop ((n n) (ns (list))) (if (or (= n 1) (member n '(4 16 37 58 89 145 42 20))) (reverse (cons n ns)) (let ((x (sum (map square (digits n))))) (loop x (cons n ns))))))
Here are two examples:
> (ssds 19) (19 82 68 100 1) > (ssds 18) (18 65 61 37)
You can run the program at https://ideone.com/Ro26ys. There is more to the topic of Happy Numbers than we have discussed here; oeis.org is a good place to learn more.
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