编写一个函数过程:判断一个已知数m是否是完数(完数就是指该数本身等于它各个因子之和,如6=1+2+3,6就是

2024-12-25 16:07:16
推荐回答(5个)
回答1:

老实说,我不懂什么是完数,但如果28算是完数的话,那我写的这段代码就可以用。

从1循环到10000,返回
6=1+2+3
6是完数
28=1+2+14+4+7
28是完数
496=1+2+248+4+124+8+62+16+31
496是完数
8128=1+2+4064+4+2032+8+1016+16+508+32+254+64+127
8128是完数

我是Text1 Text2 来输入输出的,你自己按你要求改下吧。

Private Sub Command3_Click()
Dim a, b, x, y, z As Double, m, n, ss As String
a = Text1.Text
b = 0: m = "1": z = 1
For x = 2 To a - 1
If a Mod x = 0 And a <> x Then
b = 1: y = a / x
If y > x Then n = x & "+" & y Else n = y & "+" & x '待判断是否重复后写入
If InStr(m & "+", "+" & n & "+") = 0 Then
m = m & "+" & n: z = z + x + y
End If
End If
Next
If a = 1 Then
ss = ss & "1不是素数也不是合数" & vbCrLf
ElseIf b = 1 Then
If a = z Then
ss = ss & a & "=" & m & vbCrLf
ss = ss & a & "是完数" & vbCrLf
Else
ss = ss & a & "不是完数" & vbCrLf
End If
Else
ss = ss & a & "是素数" & vbCrLf
End If
Text2.Text = ss
End Sub

回答2:

Function ws(ByVal m As Integer,st as string) As Boolean
Dim i, b As Integer
b = 2 : i = 1:st=m&"1"
Do While b * 2 <= m
If m Mod b = 0 Then
i = i + b
st=st&"+"&st(b) ‘这里虽说把有许多不符合的,但是根据你的输出,只要ws是true,它的st就是正确的。
End If
b += 1
Loop
If i = 1 Then '这个if一定要说出来,因为要把m=1在这里排除了
Exit Function
End If
If m = i Then
ws = True
End If
End Function
我把以前的改了一小点:多了个st的输出形式,把n换成m。我机子上的vb删了,没地方地方调试。配合着你的,这个直接就能用了。你试试吧。

回答3:

请见:http://baike.baidu.com/view/640632.htm

回答4:

我想请问乃是否理工的学生···

回答5:

Private Sub Command1_Click()
Dim i As Integer, st As String
For i = 1 To 100
If ws(i, st) Then Picture1.Print st
Next i
End Sub

Function ws(ByVal m%, st As String) As Boolean
st = m & "=1"
t = 1
For i = 2 To m \ 2
If m Mod i = 0 Then
st = st & "+" & i
t = t + i
End If
Next i
If m = t Then ws = True Else ws = False
End Function