Home > Mathematica, Mathematics > Happy Numbers

Happy Numbers

This post is posted by a Mathematica Stackexchange question about “happy numbers”, where a happy number (integer range 1 to 100) is a number that terminates in 1 after repeated summing of the square of its digits, e.g. 7->49->97->130->10->1. This was a nice exercise in Mathematica.

I found the happy numbers using the following code:


I felt the desire to visualize the graph of these relationships (showing the two components):

ans = NestWhileList[#.# &@IntegerDigits[#] &, #, UnsameQ[##] &,
All] & /@ Range[100];
g = DirectedEdge @@@
Union[Apply[Join, Partition[#, 2, 1] & /@ ans, {0}]];
el = VertexList[Graph[g]] /. {1 -> Style[1, Red],
4 -> Style[4, Yellow]}
Graph[el, g, VertexLabels -> Placed["Name", Center],
VertexStyle -> White, VertexSize -> 2,
GraphLayout -> "SpringEmbedding"]


Categories: Mathematica, Mathematics
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: