VB编程题 求1——1000的素数之和
哪位好心人,帮帮忙!
哪位好心人,帮帮忙!
答案:Private Sub Command1_Click()
Dim i As Integer
Dim s As Long
s = 0
For i = 1 To 1000
If IsPrime(i) Then
s = s + i
End If
Next
MsgBox "1-1000的素数之和是" & s
End Sub
Function IsPrime(ByVal n As Integer) As Boolean
Dim i As Integer
Dim f As Boolean
If n = 1 Then '如果是1,直接返回假,退出函数
IsPrime = False
Exit Function
End If
f = True '假定为真
For i = 2 To Sqr(n) '从2到n的平方根
If n Mod i = 0 Then '如果能整除,设为假,退出循环
f = False
Exit For
End If
Next
IsPrime = f
End Function