by Lorenzo Poerio Pitera' ()
Category: Math/Dates
Compatability: Visual Basic 5.0
Difficulty: Unknown Difficulty
Originally Published: Tue 28th August 2001
Date Added: Mon 8th February 2021
Rating:
(1 Votes)
This is the fastest Function to determinate if a number is Prime. It works with small and big Numbers. Is 999,999,999,999,947 prime?
' Author: Lorenzo Poerio Pitera'
' Date: 28 August 2001
' This is the fastest Function to determinate if a number is Prime.
' It works with small and big Numbers.
' Is 999,999,999,999,947 prime?
Dim i As Long, j As Long, M As Long
If N <> Int(N) Then Exit Function
If N < 2147483648# Then
' I can convert the variable type to double type
' and I can use the Mod function,
' so it gets faster to evaluate if N is prime
M = N
If M < 2 Then Exit Function
If M = 2 Then TheBestIsPrime = True: Exit Function
If M Mod 2 = 0 Then Exit Function
If M < 8 Then TheBestIsPrime = True: Exit Function
If M Mod 3 = 0 Then Exit Function
If M Mod 5 = 0 Then Exit Function
If M Mod 7 = 0 Then Exit Function
If M < 38 Then TheBestIsPrime = True: Exit Function
i = Sqr(M)
' Now I start the big loop
' Note: every 30 steps I do only 8 verifications
For j = 0 To i Step 30
If M Mod (j + 11) = 0 Then Exit Function
If M Mod (j + 13) = 0 Then Exit Function
If M Mod (j + 17) = 0 Then Exit Function
If M Mod (j + 19) = 0 Then Exit Function
If M Mod (j + 23) = 0 Then Exit Function
If M Mod (j + 29) = 0 Then Exit Function
If M Mod (j + 31) = 0 Then Exit Function
If M Mod (j + 37) = 0 Then Exit Function
Next j
Else
' The number is too Big so I can not use the Mod function. No problem:
' number Mod divisor = number - divisor * Int(number / divisor)
If N = Int(N / 2) * 2 Then Exit Function
If N = Int(N / 3) * 3 Then Exit Function
If N = Int(N / 5) * 5 Then Exit Function
If N = Int(N / 7) * 7 Then Exit Function
i = Sqr(N)
For j = 0 To i Step 30
If N = Int(N / (j + 11)) * (j + 11) Then Exit Function
If N = Int(N / (j + 13)) * (j + 13) Then Exit Function
If N = Int(N / (j + 17)) * (j + 17) Then Exit Function
If N = Int(N / (j + 19)) * (j + 19) Then Exit Function
If N = Int(N / (j + 21)) * (j + 21) Then Exit Function
If N = Int(N / (j + 29)) * (j + 29) Then Exit Function
If N = Int(N / (j + 31)) * (j + 31) Then Exit Function
If N = Int(N / (j + 37)) * (j + 37) Then Exit Function
Next j
End If
TheBestIsPrime = True
End Function
No comments have been posted about This is the fastest Function to determinate if a number is Prime. It works with small and big Numbe. Why not be the first to post a comment about This is the fastest Function to determinate if a number is Prime. It works with small and big Numbe.