怎么用VB编程实现判断一个数是否为素数

如题所述

素数的概念就是只能被1和自身整除,你是知道的,不然你不可能问这样的问题,通常用程序判断的方法就是用该数分别除从1到该整数本身的所有整数,如果发现有能够整除的,那么该数就不是素数,其实没必要挨着除完,只需要试一半,因为,如果他在一半的数中能够被某个数整除,那么他在另外一半也能,否则该数一定是素数
给你写的函数
private function IsSuShu(NB&) as boolean
if nb mod 2=0 then issushu=true:exit function
dim i&j&
j=nb\2
for i=2 to j
if nb mod i<>0 then issushu=true:exit function
next i
end function
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-06-30
Private Sub Command1_Click()
Dim N As Long, Flags As Boolean
N = Val(Text1.Text)
Flags = True
For i = 2 To Sqr(N)
If N Mod i = 0 Then
Flags = False
Exit For
End If
Next
MsgBox N & IIf(Flags, "", "不") & "是一个素数"

End Sub本回答被提问者采纳
第2个回答  2008-06-30
Private Function s(t As Integer) As Boolean
If t = 1 Or t = 2 Then s = False: Exit Function
Else: s = True
End If
For i = 2 To t - 1
If t Mod i = 0 Then
s = False: Exit Function
End If
Next
End Function

'调用函数,如果函数为true即为素数,否则不是
第3个回答  2008-06-30
求100以内的素数:
Private Sub Form_click()
Dim i As Integer, m As Integer
Dim n As Integer
n = 1
j = 0
Do
m = Sqr(n)
For i = 2 To m
If n Mod i = 0 Then GoTo lp
Next i
Print n;
j = j + 1
lp: n = n + 1
Loop While n <= 100
End Sub
相似回答