Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4,VB5,VB6,VBS
Expertise: Intermediate
May 27, 2000

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
 
Comment and Contribute

 

 

 

 

 


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

 

 

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