Public Function IsPrime(ByVal lValue As Long) As Boolean
Dim lCtr As Long
Dim lRes As Long
Dim lCount As Long
'eliminate even numbers right away
lValue = Abs(lValue)
If lValue Mod 2 = 0 Then Exit Function
For lCtr = 1 To lValue
lRes = lValue Mod lCtr
If lRes <> 0 Then
lCount = lCount + 1
End If
Next
IsPrime = (lCount = lValue - 2)
End Function
***************************************************
Second sample
***************************************************
Public Function prime(n As long) As Boolean
Dim l As Long
For l = 2 To n - 1
If n Mod l = 0 Then
prime = False
Exit Function
End If
Next l
prime = True
End Function
*******************************************************
Third sample
*******************************************************
Public Function IsPrime(TestPrime As Long) As Boolean
Dim TestNum As Long
Dim TestLimit As Long
' Eliminate even numbers
If TestPrime Mod 2 = 0 Then Exit Function
' Loop through ODD numbers starting with 3
TestNum = 3
TestLimit = TestPrime
Do While TestLimit > TestNum
If TestPrime Mod TestNum = 0 Then
' Uncomment this if you really want to know
' MsgBox "Divisible by " & TestNum
Exit Function
End If
' There's logic to this. Think about it.
TestLimit = TestPrime \ TestNum
' Remember, we only bother to check odd numbers
TestNum = TestNum + 2
Loop
' If we made it through the loop, the number is a prime.
IsPrime = True
End Function
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.