Option ExplicitSub main() Dim a(), i As Integer a = Array(1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097) For i = 0 To 15 Debug.Print a(i) Next End Sub
Private Sub Command1_Click() Dim i As Integer, j As Integer, isprime As Boolean For i = 1001 To 1100 Step 2 isprime = True For j = 3 To Sqr(i) Step 2 If i Mod j = 0 Then isprime = False Exit For End If Next If isprime = True Then Debug.Print i Next End Sub返回: 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097
Option ExplicitSub main() Dim i As Integer For i = 0 To 15 Debug.Print "10" & Mid("09131921313339495161636987919397", 1 + i * 2, 2) Next End Sub
测试一个数是否是素数:
设有一数A,测试A是否素数的方法:
从2~A的平方根,去除A,如果都不能整除,则A为素数。
For i& = 1000 To 1100
If IsPrime(i&) Then Debug.Print i& & vbCrLf
NextEnd Sub
Function IsPrime(TestNum&) As Boolean Dim A&
Dim ASqr&
Dim i&
A& = TestNum&
ASqr& = CLng(Sqr(A&))
For i& = 2 To ASqr&
If A& Mod i& = 0 Then
IsPrime = False
Exit Function
End If
Next
IsPrime = TrueEnd Function
同意一楼,简洁高效
______________________
妙!程序员都是惜字如金的人.
Dim a(), i As Integer
a = Array(1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097)
For i = 0 To 15
Debug.Print a(i)
Next
End Sub
Dim i As Integer, j As Integer, isprime As Boolean
For i = 1001 To 1100 Step 2
isprime = True
For j = 3 To Sqr(i) Step 2
If i Mod j = 0 Then
isprime = False
Exit For
End If
Next
If isprime = True Then Debug.Print i
Next
End Sub返回: 1009
1013
1019
1021
1031
1033
1039
1049
1051
1061
1063
1069
1087
1091
1093
1097
Dim i As Integer
For i = 0 To 15
Debug.Print "10" & Mid("09131921313339495161636987919397", 1 + i * 2, 2)
Next
End Sub