How do you determine if a number is a perfect number in…

In VB, you can determine whether a number is a perfect number using the following method:

  1. Firstly, define a function that checks if a number is a perfect number, with the function parameter being an integer. The internal logic of the function is as follows:
Function IsPerfectNumber(num As Integer) As Boolean
    Dim sum As Integer = 0
    For i As Integer = 1 To num - 1
        If num Mod i = 0 Then
            sum += i
        End If
    Next
    If sum = num Then
        Return True
    Else
        Return False
    End If
End Function
  1. Next, call this function in the main program, passing in the number to be checked. If the result is True, it means the number is a perfect number, and if it is False, it means the number is not a perfect number.
Sub Main()
    Dim num As Integer = 28
    If IsPerfectNumber(num) Then
        Console.WriteLine(num & "是完数")
    Else
        Console.WriteLine(num & "不是完数")
    End If
End Sub

In the example above, the number being evaluated is 28. According to the definition of perfect numbers, the sum of all factors of 28 (excluding 28 itself) is 1+2+4+7+14=28. Therefore, 28 is a perfect number, and the output is “28 is a perfect number.”

bannerAds