回复 10楼 风吹过b
好的,我加了控件,试验了一下,可以运行了:Option Explicit
Dim Ssb() As Long '素数表,1亿以内素数表,一共5761455个
Dim ssbj As Long
Dim b2b(30) As Long '2的倍数表,long 范围最大只能容纳 2^31,但最后一个数用不了,会超范围
Const 范围 As Long = 10000 '1亿以内,我光生成素数表就用了超过4分钟。你要测试1亿,直接把这1万改成1亿吧
Private Sub Command1_Click()
Dim i As Long, j As Long, o As Long, t As Long, ja
Dim fly As Boolean, flj As Long, fl() As Long
flj = 0
ReDim fl(flj)
Call 日志("开始生成素数表")
Call 生成素数表
Call 日志("开始生成2的倍数表")
Call 生成倍数表
Call 日志("开始计算....")
For i = 5 To 范围 Step 2
j = 1
fly = False '假设不符合
Do While i > Ssb(j)
t = i - Ssb(j)
For o = 0 To 30 '这里会浪费循环次数,不管了
If t = b2b(o) Then
fly = True '找到符合
Exit For '不再查找
End If
Next o
If fly Then Exit Do '找到符合不再查找
j = j + 1
Loop
If Not fly Then '如果都没找到
flj = flj + 1 '保存结果
ReDim Preserve fl(flj)
fl(flj) = i
Call 日志("找到第 " & flj & " 个: " & i) '显示结果,注意 日志过程中有 DoEvents 命令,会拖慢运算速度
End If
Next i
Call 日志("完成查找,共找到 " & flj & " 个。")
Text1 = flj
Combo1 = List1.ListCount
End Sub
Private Sub 生成倍数表()
'如果有倍数表,则不再生成
If b2b(30) > 0 Then Exit Sub
Dim i As Long
For i = 0 To 30
b2b(i) = 2 ^ i
Next i
End Sub
Private Sub 生成素数表()
'如果已经有素数表,则不再生成
If ssbj > 3 Then Exit Sub
Dim i As Long, j As Long, t As Long, ja
Dim sy As Boolean
'素数从2开始,需要指定
ssbj = 1
ReDim Ssb(ssbj)
Ssb(1) = 2
For i = 3 To 范围 Step 2
sy = True
t = Sqr(i)
For j = 3 To ssbj
If t < Ssb(j) Then Exit For
If i Mod Ssb(j) = 0 Then
sy = False
Exit For
End If
Next j
If sy Then
ssbj = ssbj + 1
ReDim Preserve Ssb(ssbj)
Ssb(ssbj) = i
ja = " " & i '增加一条
End If
Next i
End Sub
Private Sub 日志(cs As String)
With List1
If .ListCount >= 100 Then
.RemoveItem 0
End If
.AddItem Now & " " & cs
DoEvents
End With
End Sub
'加了控件list1就可以运行了,结果是找到26个符合条件的素数。