求1000 以内的 素数的 vb 函数

来源:百度知道 编辑:UC知道 时间:2024/05/19 23:49:32

'不需要任何控件,执行即可出结果
Private Sub Form_Activate()
Dim np As Integer 'np存放素数个数
np = 0

Print "1000以内的素数为"
For i = 2 To 1000
If isprime(i) Then
np = np + 1
Print i; Space(4 - Len(i));
If np Mod 10 = 0 Then Print
End If
Next

Print
Print "素数个数为"; np

End Sub

Function isprime(ByVal Num As Integer) As Boolean '判断是否为素数的函数
If Num < 2 Then isprime = False: Exit Function

Dim i As Integer

For i = 2 To Sqr(Num)
If (Num Mod i) = 0 Then
isprime = False
Exit Function
End If
Next i

isprime = True
End Function