How to find all happy numbers in a specific range with VB.NET

1 Answer

0 votes
Imports System
Imports 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

Module HappyNumbers

    ' Compute the sum of squares of digits of n
    Function SumOfDigitSquares(n As Integer) As Integer
        Dim sum As Integer = 0
        While n > 0
            Dim d As Integer = n Mod 10
            sum += d * d
            n \= 10
        End While
        Return sum
    End Function

    ' Determine whether n is a happy number
    Function IsHappy(n As Integer) As Boolean
        Dim seen As New HashSet(Of Integer)()

        While n <> 1 AndAlso Not seen.Contains(n)
            seen.Add(n)
            n = SumOfDigitSquares(n)
        End While

        Return n = 1
    End Function

    Sub Main()
        Dim a As Integer = 1
        Dim b As Integer = 100

        If a > b Then
            Dim temp = a
            a = b
            b = temp
        End If

        Dim happyNumbers As New List(Of Integer)()

        For i As Integer = a To b
            If IsHappy(i) Then
                happyNumbers.Add(i)
            End If
        Next

        Console.WriteLine($"Happy numbers in range [{a}, {b}]:")
        For Each n In happyNumbers
            Console.Write(n & " ")
        Next
    End Sub

End Module


'
' 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
...