Determine if a number is prime
Determine if a number is a prime:
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
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
评论
发表评论