Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

do anyone know how to determine if

  • Thread starter Thread starter WC
  • Start date Start date
Status
Not open for further replies.

WC

Programmer
Joined
Sep 19, 2001
Messages
9
Location
SG
do anyone know how to determine if a number is a prime number or not in vb
 
Hi,

There are several ways of doing this
Here's some code

*******************************************************

Public Function IsPrime(ByVal lValue As Long) As Boolean
Dim lCtr As Long
Dim lRes As Long
Dim lCount As Long
'eliminate even numbers right away
lValue = Abs(lValue)
If lValue Mod 2 = 0 Then Exit Function
For lCtr = 1 To lValue
lRes = lValue Mod lCtr
If lRes <> 0 Then
lCount = lCount + 1
End If
Next
IsPrime = (lCount = lValue - 2)
End Function

***************************************************
Second sample
***************************************************

Public Function prime(n As long) As Boolean
Dim l As Long
For l = 2 To n - 1
If n Mod l = 0 Then
prime = False
Exit Function
End If
Next l
prime = True
End Function

*******************************************************
Third sample
*******************************************************

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 &quot;Divisible by &quot; & 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

*****************************************************

Hope this helps
Good luck
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top