■当前位置:首页 > VB
小程序 >
VB查找素数:速度最快的代码
2. VB查找素数:速度最快的代码
'本人认为这是效率最高,速度最快的代码。如果有朋友另有高见,欢迎指教。
'程序要求:
' 1 查找 N 以内的所有素数,存入数组
Su(),计算查找总时间
' 2.将查找结果显示到列表框
' 3.查找和添加列表框的过程中有进度显示
''以下代码在 VB6 调试通过。
' 需要在窗体放置4个控件,不用设置控件任何属性:Command1,Command2,List1,Label1
Dim ctExit As Boolean, ctStop As Boolean
Dim ctCiFind As Long, ctCiAdd As Long
Private Sub Form_Load()
Me.Caption
= "查找 N 以内的所有素数"
Label1.Caption
= Me.Caption: Label1.AutoSize = True
Command1.Caption
= "查找": Command2.Caption = "取消"
End Sub
Private Sub Form_Resize()
Dim S As
Long
On Error
Resume Next
S =
Me.TextWidth("A")
Command1.Move
S, S, S * 8, S * 3
Command2.Move
S * 10, S, S * 8, S * 3
Label1.Move
S, Me.ScaleHeight - S * 4, Label1.Width, S * 4
List1.Move 0,
S * 5, Me.ScaleWidth, Label1.Top - S * 5
End Sub
Private Sub Form_Unload(Cancel As Integer)
ctExit
= True: ctStop = True '保证在查找未结束时能顺利结束程序
End Sub
Private Sub Command2_Click()
ctStop = True
'取消查找
End Sub
Private Sub Command1_Click()
Static N As
Long
Dim Su() As
Long, S As Long, Gen As Long, I As Long, J As Long
Dim nStr As
String, T As Single, Ci As Long
'查找 N 以内的所有素数,存入数组 Su(),素数的总个数为 S
If N
< 2 Then N = 10000
nStr =
InputBox("请输入一个大于 1 的整数:", "查找素数", N)
If nStr = ""
Then Exit Sub
N =
Val(nStr)
S = 0: ReDim
Su(1)
If N
> 1 then S = 1: Su(1)=2 '■■根据冰麟轻武的建议,添加了本行
ctStop
= False: Command1.Enabled = False
List1.Clear:
Label1.Caption = "正在查找 " & N & "
以内的素数 ..."
DoEvents
T =
Timer
If ctCiFind
< 10000 Then ctCiFind = 10000
'For I = 2 To N
For I = 3 To
N Step 2 '■■根据冰麟轻武的建议,将上一行语句改成了本行
Gen
=
Sqr(I) '记忆
I 的平方根
For
J = 1 To S
'进度显示
Ci
= Ci + 1
If
Ci > ctCiFind Then
Ci
= 0: DoEvents
If
ctStop Then GoTo Show1
Label1.Caption
= N & " 以内的素数:" & S
& " 个," & Format(I / N * 100,
"0.0") & "%"
End
If
'用
I 除以已经找到的素数■■交换下面两行代码,似乎能减少一次 Mod 运算
If
I Mod Su(J) = 0 Then GoTo NextI '能整除,不是素数,检查下一个
If
Su(J) > Gen Then Exit
For '检测到大于
I 的平方根就不用查了。删除此语句,结果一样,但速度慢得多
Next
S
= S + 1: ReDim Preserve Su(S): Su(S) = I
NextI:
Next
I = N
'将找到的素数显示到列表框中
Show1: