sorry,写错了,更正如下:
Function primeStatus(a As Integer) As Boolean
Dim i As Integer
Dim j As Integer
For i = 2 To a - 1
If a Mod i = 0 Then
primeStatus = False
Exit Function
End If
Next i
primeStatus = True
End Function
Private Sub Command1_Click()
Dim i As Integer
Dim j As Integer
For i = 500 To 1000 Step 2
For j = 1 To i - 1
If primeStatus(j) Then
If primeStatus(i - j) Then
Debug.Print i & " = " & j & " + " & (i - j)
End If
End If
Next j
Next i
End Sub
一个判断数值是否为素数的Function:
Function PrimeStatus(TestVal As Long) As Boolean
Dim i As Long
Dim Lim As Integer
PrimeStatus = True
Lim = Sqr(TestVal)
For i = 2 To Lim
If TestVal Mod i = 0 Then
PrimeStatus = False
Exit For
End If
Next
End Function
如果要产生素数数组可以这样:
Function arrPrime1(ByVal num As Long) As Long()
Dim i As Long
Dim k As Long
Dim arrPrime() As Long
k = 0
For i = 2 To num
If PrimeStatus(i) = True Then
ReDim Preserve arrPrime(k)
arrPrime(k) = i
k = k + 1
End If
Next
arrPrime1 = arrPrime
End Function
Private Sub Command5_Click()
Dim iloop As Integer
Dim jloop As Integer
Dim kloop As Integer
Dim flag1 As Boolean
Dim flag2 As Boolean
For iloop = 500 To 1000 Step 2
For jloop = 3 To iloop Step 2
flag1 = True
For kloop = 2 To jloop - 1
If (jloop Mod kloop) = 0 Then
flag1 = False
'Exit For
End If
Next kloop
If flag1 = True Then
flag2 = True
For kloop = 2 To iloop - jloop - 1
If ((iloop - jloop) Mod kloop) = 0 Then
flag2 = False
'Exit For
End If
Next kloop
If flag2 = True Then
Debug.Print jloop & " " & iloop - jloop
End If
End If
If flag2 = True Then
Exit For
End If
Next jloop
Next iloop
End Sub
Private Sub Command3_Click()
Dim i As Integer
Dim j As Integer
For i = 500 To 1000
For j = 3 To i / 2 Step 2
If s(j) = True Then
If s(i - j) = True Then
Debug.Print j, i - j
Exit For
End If
End If
Next
Next
End Sub
Private Function s(a As Integer) As Boolean
Dim i As Integer
Dim j As Integer
Dim k As Integer
If a = 3 Then
s = True
Exit Function
End If
If a = 2 Then
s = True
Exit Function
End If
k = a / 2
If (a Mod 2) = 0 Then
s = False
Exit Function
End If
For i = 3 To k Step 2
If (CInt(a / i)) * i = a Then
s = False
Exit Function
End If
Next
s = True
End Function