What are Happy Numbers?
Let us take the number 79. If we square each of the digits and add them, we get 7×7 + 9×9 = 49 + 81 = 130. Let us denote this transformation T(n). Hence, T(79) = 130. Now let us do the same for 130. We get 1 + 9 + 0 = 10. Doing again for 10, we get 1 + 0 = 1. So, if we start with a number n, and end with 1, the number n and all the numbers in the chain are called happy numbers.
79 ⟼ 130 ⟼ 10 ⟼ 1
However, if we start with the number 80, we get something interesting. The chain gets into a loop and gets stuck there.
80 ⟼ 64 ⟼ 52 ⟼ 29 ⟼ 85 ⟼ 89 ⟼ 145 ⟼ 42 ⟼ 20 ⟼ 4 ⟼ 16 ⟼ 37 ⟼ 58 ⟼ 89
Now we could think that in the former case, it got into a loop at 1 and got stuck there. It turns out there are only two loops that any natural number can get stuck – [1] and [89, 145, 42, 20, 4, 16, 37, 58]. If we add 0 to the mix, then also [0].
Visualization
I was thinking wouldn’t it be cool to see all these chains visually? So I wrote a small program that would create a simple digraph with numbers as nodes and each edge corresponding to a number n and T(n).
I created a graph for 0 <= n <=200. When I rendered it with dot (Graphviz), it gave me this spectacular visual! As expected, we could see 3 clusters. The tiniest one has only one number 0. The small cluster consists of all happy numbers. The larger one is all unhappy numbers.
![](http://geekraj.com/wp-content/uploads/2021/12/screen1-1024x718.png)
Zooming into the loop at the center of unhappy numbers, we see the sequence I mentioned earlier [89, 145, 42, 20, 4, 16, 37, 58].
![](http://geekraj.com/wp-content/uploads/2021/12/screen2-1024x655.png)
Code
I have used a d3 port of Graphviz to render the graph on the browser. You can find the code here: https://github.com/rmadhuram/happy-numbers
Graphviz is an open-source graph visualization software developed by AT & T Research.
D3 is a JavaScript library for visualizing data with HTML, SVG, and CSS.
d3-graphviz renders SVG from graphs described in the DOT language using the @hpcc-js/wasm port of Graphviz and does animated transitions between graphs.
Future Work
If I try to render more than 200 numbers, say 250, 500, etc., the rendering is not clean. I have an idea for an algorithm that could do a better graph layout for these types of structures. I hope to implement it when I find some time!