How to print all the happy numbers between 1 and N in VB.NET

1 Answer

0 votes
' 8^2 + 2^2 = 68
' 6^2 + 8^2 = 100
' 1^2 + 0^2 + 0^2 = 1 = happy number

Imports System

Public Class Program
    Public Shared Function isHappyNumber(ByVal num As Integer) As Integer
        Dim sum As Integer = 0

        While num > 0
            Dim reminder As Integer = num Mod 10
            sum = sum + (reminder * reminder)
            num = num \ 10
        End While

        Return sum
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim N As Integer = 100

        For i As Integer = 1 To N
            Dim num As Integer = i
            Dim result As Integer = num

            While result <> 1 AndAlso result <> 4
                result = isHappyNumber(result)
            End While

            If result = 1 Then
                Console.Write(num & " ")
            End If
        Next
    End Sub
End Class





' run:
'
' 1 7 10 13 19 23 28 31 32 44 49 68 70 79 82 86 91 94 97 100
'

 



answered Nov 15, 2022 by avibootz
...