How to find all happy numbers in a specific range with C#

1 Answer

0 votes
using System;
using System.Collections.Generic;

// A happy number is a number that eventually reaches 1 
// when repeatedly replaced by the sum of the squares of its digits.
//
// 19 = 1^2 + 9^2 = 82
// 19 -> 82 -> 68 ->100 -> 1 eventually reaches 1 
// 19 = happy numbe

class HappyNumbers
{
    // Compute the sum of squares of digits of n
    static int SumOfDigitSquares(int n)
    {
        int sum = 0;
        while (n > 0) {
            int d = n % 10;
            sum += d * d;
            n /= 10;
        }
        return sum;
    }

    // Determine whether n is a happy number
    static bool IsHappy(int n)
    {
        HashSet<int> seen = new HashSet<int>();

        while (n != 1 && !seen.Contains(n)) {
            seen.Add(n);
            n = SumOfDigitSquares(n);
        }
        return n == 1;
    }

    static void Main() {
        int a = 1, b = 100;

        if (a > b) {
            int temp = a;
            a = b;
            b = temp;
        }

        List<int> happyNumbers = new List<int>();

        for (int i = a; i <= b; i++) {
            if (IsHappy(i)) {
                happyNumbers.Add(i);
            }
        }

        Console.WriteLine($"Happy numbers in range [{a}, {b}]:");
        foreach (int n in happyNumbers) {
            Console.Write(n + " ");
        }
    }
}



/*
run:

Happy numbers in range [1, 100]:
1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100 

*/

 



answered Feb 24 by avibootz
...