Find happy numbers in C#


[happy numbers]

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.

72 = 49
42 + 92 = 97
92 + 72 = 130
12 + 32 + 02 = 10
12 + 02 = 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.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in algorithms, mathematics and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.