VBA - A Function to Check whether a Given Number is Prime
Below is an optimized function to check on the primality of a number. This function takes input number as Double, hence can be used to check upto a number having 15 significant digits. Whereas Long can take up to a maximum of 10 significant digits and maximum number it can support is 2,147,483,648.
First function is when pure number is passed, hence argument can be declared as Double. Hence, you will have to pass the value not the range.
Second function is when variant is passed as argument so that even range can be passed in this function.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Function IsPrime(Num As Double) As Boolean Dim i As Double If Int(Num / 2) = (Num / 2) Then Exit Function Else For i = 3 To Sqr(Num) Step 2 If Int(Num / i) = (Num / i) Then Exit Function End If Next i End If IsPrime = True End Function |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Function IsPrimeV(Num) As Boolean Dim i As Double If Int(Num / 2) = (Num / 2) Then Exit Function Else For i = 3 To Sqr(Num) Step 2 If Int(Num / i) = (Num / i) Then Exit Function End If Next i End If IsPrimeV = True End Function |
Below is time performance for both functions -
The file used for checking time performance - Prime Number Checker