VB编程:输出1~100之间所有素数

如题.

查找1到1000的素数显示到文本框,瞬间完成
'例子需控件:Command1、Text1

Private Sub Command1_Click()
Dim a() As Long, nStr As String

'Call FindSuShu(18, 100, a, 5) '查找大于17的5个素数存入数组a
Call FindSuShu(1, 1000, a) '查找1到1000之间的所有个素数

'显示到 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
'来源:我的QQ http://new.qzone.qq.com/32063270/blog/1222349880
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-10-07
Dim a As Double
Dim b As Double
Dim c As Double
Dim d As Double
Dim t As Double
Dim Uu9 As String
Private Sub Form_Click()
a = 1
b = 100
If b > 90000 Then
daan = MsgBox("判断大于90000的数将用较长时间" + vbCrLf + " 继续吗?", 36, "询问")
If daan = vbNo Then
Exit Sub
End If
End If
If a >= b Then
t = a
a = b
b = t
'MsgBox "第一个数应比第二个数小!", 16, "数据错误"
'Exit Sub
End If
If a <= 2 Then
Uu9 = "2"
a = 2
End If
For c = a To b
bz = False
If c / 2 = c \ 2 Then
bz = True
End If

For d = 3 To Int(Sqr(c)) Step 2
If c / d = c \ d Then
bz = True
d = c
End If
DoEvents
Next d
If bz = False Then
Uu9 = Uu9 & " " & Str(c)
End If
Next c
Print Uu9
End Sub

Private Sub Form_Load()
Me.Width = 10000
Me.Height = 1000
End Sub
第2个回答  2008-10-07
dim i as integer,j as integer
dim b as boolean

for i=2 to 100
b=true
for j=2 to int(sqrt(i))
if i mod j=0 then b=false:exit for
next
if b then print i & " "
next本回答被网友采纳
第3个回答  2008-10-07
Function Sushu(Nums As Integer) As Boolean '判断是否是素数
Sushu = False
For i = 2 To Sqr(Nums)
If Nums Mod i = 0 Then
Exit Function
End If
Next i
Sushu = True
End Function

Private Sub Form_Load()
Dim i As Integer
For i = 1 To 100
If Sushu(i) = True Then
MsgBox i'你也可以换成你自己的输出方式
End If
Next i
End Sub