Private Sub Command1_Click()
Dim i As Long, j As Long, k As Long
Dim ZT As Boolean
For i = 10 To 100
j = Sqr(i)
ZT = True
For k = 2 To j
If i Mod k = 0 Then
ZT = False
Exit For
End If
Next
If ZT Then Print i
Next
End Sub
Private Sub Command2_Click()
Dim i As Long
For i = 10 To 100
If SS(i) Then Print i
Next
End Sub
Function SS(n As Long) As Boolean
Dim i As Long, j As Long, k As Long
j = Sqr(n)
SS = True
For i = 2 To j
If n Mod i = 0 Then
SS = False
Exit For
End If
Next
End Function
第一个按钮是用循环的,第二个按钮是调用SS函数的
'查找指定范围的素数存入数组
'例子需控件:Command1、Text1
Private Sub Command1_Click()
Dim a() As Long, nStr As String
'Call FindSuShu(18, 100, a, 5) '查找大于17的5个素数存入数组a
Call FindSuShu(10, 100, a) '查找10到100之间的所有个素数
'显示到 Text1
For I = LBound(a) To UBound(a)
nStr = nStr & a(I) & " "
Next
Text1.Text = nStr
End Sub
Private Sub FindSuShu(FromS As Long, ToS As Long, Su() As Long, Optional Ge As Long)
'查找位于 FromS 和 ToS 之间的质数(素数),存入数组 Su()
'Ge 表示查找个数, 如果指定 Ge,则忽略 ToS
Dim I As Long, J As Long, SuAll() As Long, S As Long, MaxN As Long
Dim ReS As Long
S = 1
ReDim SuAll(1 To 1): SuAll(1) = 2
ReDim Su(1 To 1)
If FromS <= 2 And ToS >= 2 Then ReS = 1: Su(1) = 2
I = 2
Do
DoEvents
I = I + 1
If Ge < 1 And I > ToS Then Exit Do
MaxN = I ^ 0.5 '比较 I 的一半
For J = 1 To S
If I Mod SuAll(J) = 0 Then GoTo NextI '不是质数
If SuAll(J) > MaxN Then Exit For '是质数
Next J
S = S + 1 '找到质数的总个数
ReDim Preserve SuAll(1 To S)
SuAll(S) = I
If I < FromS Then GoTo NextI
ReS = ReS + 1 '返回质数的总个数
ReDim Preserve Su(1 To ReS)
Su(ReS) = I
If Ge > 0 And ReS >= Ge Then Exit Do
NextI:
Loop
End Sub
用函数:
private function su(byval n as integer) as boolean
dim i as integer
for i=2 to sqr(n)
if n mod i=0 then
su=false
exit function
end if
next i
su=true
end function
private sub command1_click()'按钮的单击事件
dim i as integer
for i=10 to 100
if su(i) then print i;
next i
end sub
用循环:
Private Sub command1_click() '按钮的单击事件
Dim i As Integer, j As Integer
For i = 10 To 100
For j = 2 To Sqr(i)
If i Mod j = 0 Then
Exit For
End If
Next j
If j > Sqr(i) Then Print i;
Next i
End Sub