vb编程,找出介于A B之间的所有只有素数因子(1和自身除外)的数。哪点错了,为什么没有输出
Private Sub Command1_Click()
Dim i As Integer, j As Integer, n As Integer, a As Integer, b As Integer, k As Integer, c() As Integer
a = Text1: b = Text2
For n = a To b
k = 0
If prime(n) Then Exit Sub
For i = 2 To n - 1
If n Mod i = 0 Then
If prime(i) Then
k = k & i & ","
Else
Exit Sub
End If
End If
Next i
List1.AddItem n & "的素数因子是:" & k
Next n
End Sub
Private Function prime(n As Integer) As Boolean
Dim i As Integer
For i = 2 To Sqr(n)
If n Mod i = 0 Then Exit Function
Next i
prime = True
End Function
Private Sub Command2_Click()
Text1 = "": Text2 = "": List1.Clear
Text1.SetFocus
End Sub
Private Sub Command3_Click()
End
End Sub 展开
楼主,这段代码有 4 处错误。
1、将K声明为Integer(k As Integer)。而后的运算中k是当作字符串的,参加字符串运算
k = k & i & ","
这个运算,当然结果是错误的。
2、 If prime(n) Then Exit Sub,如果n是素数,就退出整个过程。n本身是素数,还需要进行n之后数据的处理呀!
3、这个If块中的是错误的 Exit Sub是错误的。也就是说某一个数有非素数因子,就退出整个过程,以后合法的数据也不在理会了。这当然是错误的。应该是Exit For。
If prime(i) Then
k = k & i & ","
Else
Exit Sub
End If
4、其实这里还隐含了以个错误。3中将Exit Sub改为Exit For,我们就看出了这个问题:发现了非素数以后,是不是还要向ListBox中加入k呢?回答是:当然不加!
那么就需要加以判断。
上述四个问题修改了以后,程序运行正常了。正确代码如下:
Option Explicit
Private Sub Command1_Click()
Dim i As Integer, j As Integer, n As Integer, a As Integer, b As Integer, c() As Integer
Dim k As String
Dim bln As Boolean
a = Text1: b = Text2
For n = a To b
k = 0
If Not prime(n) Then
bln = True
For i = 2 To n - 1
If n Mod i = 0 Then
If prime(i) Then
k = k & i & ","
Else
bln = False
Exit For
End If
End If
Next i
If bln Then List1.AddItem n & "的素数因子是:" & k '只有素数因子
End If
Next n
End Sub
'判断一个数是不是素数。是,返回True;不是,返回False
Private Function prime(n As Integer) As Boolean
Dim i As Integer
For i = 2 To Sqr(n)
If n Mod i = 0 Then Exit Function
Next i
prime = True
End Function
Private Sub Command2_Click()
Text1 = "": Text2 = "": List1.Clear
Text1.SetFocus
End Sub
Private Sub Command3_Click()
End
End Sub
for n =A to B step 2
k=int(sqr(n))
i=2
while i<=k
if n mod i = 0 then
print i **就是素数
else
i=i+1
end if
wend
next n
这样简单些。。。没必要去循环每个数。。。
突然脑子短路了。。。。。楼主私信我。。我们私聊。。一下想不起来了
Private Sub Command1_Click()
Dim i As Integer, j As Integer, n As Integer, a As Integer, b As Integer, k As Integer, c() As Integer
a = Val(Text1.Text)
b = Val(Text2.Text)
For n = a To b
i = prime(n)
If i <> n Then
k = n / i
If prime(k) = k Then
If i < k Then
List1.AddItem n & "的素数因子是:" & i & "和" & k
Else
List1.AddItem n & "的素数因子是:" & i
End If
End If
End If
Next n
End Sub
Private Function prime(n As Integer) As Integer '返回n除1以外的最小因子,若n是素数,则prime(n) = n
Dim i As Integer
For i = 2 To Sqr(n)
If n Mod i = 0 Then
prime = i
Exit Function
End If
Next i
prime = n
End Function
If prime(i) Then
k = k & i & "," '符合条件时
Else
Exit Sub ‘ 当有不符合条件的情况,直接退出子程序了,不进行下一条判断,因此问题出在该句。
End If
改为:
If prime(i) Then
k = k & i & ","
Else
Exit For
End If
就可以了。