VB 求500以内最大的10个素数,并求和

来源:百度知道 编辑:UC知道 时间:2024/06/06 17:09:36
只求速度解答

Private Sub Command1_Click()
Dim i As Long, k As Integer, s As Integer
For i = 500 To 1 Step -1
If isPrime(i) Then
k = k + 1
s = s + i
Print "第"; k; "个素数 "; i
If k = 10 Then Exit For
End If
Next i
Print "这10个素数的和是 "; s
End Sub
Private Function isPrime(lNum As Long) As Boolean
Dim lTmp As Long
isPrime = False '可以不写该句
If lNum = 2 Then
isPrime = True
ElseIf lNum > 2 And lNum Mod 2 <> 0 Then
For lTmp = 3 To Int(Sqr(lNum)) Step 2
If lNum Mod lTmp = 0 Then Exit For
Next lTmp
If lTmp > Int(Sqr(lNum)) Then isPrime = True
End If
End Function

Private Sub form_click()
Dim n As Integer, i As Integer, k As Integer, a() As Integer
For n = 2 To 500
k = Sqr(n)
For i = 2 To k
If n Mod i = 0 Then Exit For
Next i
If i > k Then
ReDim Preserve a(x)
a(x) = n
x = x + 1
End If
Nex