Before I show you the code, let me explain what happy numbers are.

# Happy Numbers

To find happy numbers, start with any integer. Replace it with the sum of the squares off its digits. Repeat the process until the numbers repeat or reach the value 1 (after which the 1 repeats). Happy numbers are those that reach 1. Other values are unhappy or sad numbers.

For example, the following values show the happy sequences of numbers starting with 7.

7^{2}= 49 4^{2}+ 9^{2}= 97 9^{2}+ 7^{2}= 130 1^{2}+ 3^{2}+ 0^{2}= 10 1^{2}+ 0^{2}= 1

This program graphs the places where the loops start and their lengths for happy numbers. For example, the equations above shows that the value 7 enters a loop after 5 steps and the loop has length 1 (because 1 just repeats).

Unhappy numbers eventually enter the loop 4, 16, 37, 58, 89, 145, 42, 20, 4, …

The program graphs the numbers’ starting points in red and the lengths of the cycles in blue. You can spot the happy numbers in the list on the left by looking for the ones with length equal to 1. The list highlights prime numbers in pink so you can pick out the happy primes.

# Code

When you click the Go button, the program loops through values from 1 to the maximum value that you enter in the text box. For each value, the program calls the following `FindHappyLoop` method.

// Return the length and start position of the number's happy loop. private List<int> FindHappyLoop(int num, out int loop_start, out int loop_length) { List<int> list = new List<int>(); list.Add(num); for (; ; ) { string str = num.ToString(); num = 0; foreach (char ch in str) { int digit = int.Parse(ch.ToString()); num += digit * digit; } if (list.Contains(num)) { loop_start = list.IndexOf(num); loop_length = list.Count - loop_start; return list; } list.Add(num); } }

This method creates a list to hold the values in the number’s happy sequence. It then enters an infinite loop.

Inside the loop, the code converts the number into a string and then loops through its digits. It converts each digit into a number, squares it, and adds it to the variable `num`.

The final value of `num` is the next value in the number’s happy sequence. If that number is already in the sequence, the sequence has entered a loop. In that case, the method sets the loop’s start position and length and then returns.

The rest of the program is relatively straightforward, so I won’t show it here. Download the example to see additional details such as how the program builds the list on the left and how it draws the graph.