Option Base 1
Public Function prime(x As Integer) '判断一个数是否为素数
k = Int(Sqr(x) + 0.5)
For i = 2 To k
If x Mod i = 0 Then
prime = False
Exit Function
End If
Next
prime = True
End Function
Private Sub Command1_Click() '调用
Dim i As Integer
For i = 2 To 100
If prime(i) Then '如果i是素数
If j = 10 Then '输出10个数为一行
Print vbCrLf
j = 0
End If
Print i;
j = j + 1
End If
Next i
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
private function Prime(byval x as long) as bool
dim i as long
for i=2 to x-1
if x mod i=0 then
Prime=false
exit function
end if
next i
Prime=true
end function
恩 可以
Private Function Prime(x As Integer) As Boolean
Dim iMin As Integer, iMax As Integer
If x < 2 Or x > 100 Then
Prime = False
Exit Function
End If
iMin = 2
iMax = Int(Sqr(x))
Dim i As Integer, bPrime As Boolean, iMod As Integer
bPrime = True
For i = iMin To iMax Step 1
iMod = x Mod i
If iMod = 0 Then bPrime = False
Next
If bPrime Then
Prime = True
Exit Function
Else
Prime = False
End If
End Function
在VB中调试通过
Dim i As Integer
For i = 1 To 100
If Prime(i) Then Debug.Print i
Next
输出100以内所有素数
不懂可以联系我,我会尽力帮你解答!