在VB中,可以通過以下方式判斷一個數(shù)是否是完數(shù):
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
Sub Main()
Dim num As Integer = 28
If IsPerfectNumber(num) Then
Console.WriteLine(num & "是完數(shù)")
Else
Console.WriteLine(num & "不是完數(shù)")
End If
End Sub
在上述例子中,判斷的數(shù)為28,根據(jù)完數(shù)的定義,28的因子(除了28本身外的所有正因子)之和為1+2+4+7+14=28,因此28是完數(shù),輸出結果為"28是完數(shù)"。