VB编程:求1000以内所有完数的个数及他们的和

2024-11-23 13:31:47
推荐回答(2个)
回答1:

Const M As Long = 1000
Dim i As Long, j As Long, k As Long
Dim A As Long, B As Long, C As Long

B = 0
C = 0
For A = 1 To M
k = Int(A / 2)
j = 0
For i = 1 To k
If A Mod i = 0 Then j = j + i
Next i
If A = j Then
B = B + 1
C = C + A
End If
Next A
MsgBox "1到" & CStr(M) & "之间共有" & CStr(B) & "个完数(也叫完全数),他们的和为" & CStr(C)

回答2:

Private Sub Command1_Click()
   Dim i, j, sum, sum1, sum2
   For i = 1 To 1000
       sum = 0
       For j = 1 To i / 2
           If i Mod j = 0 Then sum = sum + j
      Next
      
      If sum = i Then
         sum1 = sum1 + 1
         sum2 = sum2 + i
      End If
  Next
  Print "个数:"; sum1
  Print "总和:"; sum2
  
End Sub