TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » .NET » VB.NET » Math Processing
Language: VB4,VB5,VB6,VBS
Expertise: Intermediate
May 27, 2000

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# IsPrime - Determine whether a number is prime

``````' Return True if the number is prime

Function IsPrime(ByVal number As Long) As Boolean
' manually test 2 and 3
If number > 3 Then
If number Mod 2 = 0 Then Exit Function
If number Mod 3 = 0 Then Exit Function
End If
' we can now avoid to consider multiples
' of 2 and 3. This can be done really simply
' by starting at 5 and incrementing by 2 and 4
' alternatively, that is:
'    5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, ...
Dim divisor As Long
Dim increment As Long
Dim maxDivisor As Long

divisor = 5
increment = 2
' we don't need to go higher than the square
' root of the number
maxDivisor = Sqr(number) + 1

Do Until divisor > maxDivisor
If number Mod divisor = 0 Then Exit Function
divisor = divisor + increment
' this modifies 2 into 4 and viceversa
increment = 6 - increment
Loop

' if we get here, the number is prime
IsPrime = True

End Function
``````
Francesco Balena

 Submit a Tip Browse ".NET" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date