#### Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

# Prime Numbers

Member Posts: 33
Is there a VB program out there (that I can edit, if necessary) that calculates all prime numbers in a given range?

• Member Posts: 2,444
: Is there a VB program out there (that I can edit, if necessary) that calculates all prime numbers in a given range?
:

Such a program shouldn't be to hard to make?
Now I don't directly know of an efficient algorithm, but a very simple slow one would be to check for every number if it divides in a whole number. Once it does, you know it's not a prime number, given that you don't divide it by one or itself.

Should be simple right?

Greets...
Richard

• Member Posts: 2,900
: Is there a VB program out there (that I can edit, if necessary) that calculates all prime numbers in a given range?

Here's something I just hacked out in Python and translated to VB.

[code]
Public Function IsPrime(ByVal lngNum As Long) As Boolean
Const kstrProcedureName = "IsPrime"

Dim blnReturnValue As Boolean
Dim i As Long

'smallest prime is 2
If lngNum < 2 Then
blnReturnValue = False
GoTo ProcedureExit
End If

'2 is prime
If lngNum = 2 Then
blnReturnValue = True
GoTo ProcedureExit
End If

'even numbers above 2 are not prime
If lngNum Mod 2 = 0 Then
blnReturnValue = False
GoTo ProcedureExit
End If

'look for numbers that evenly divide our candidate
For i = 3 To lngNum
If i * i > lngNum Then
'if we passed the square root of the candidate without finding
'an even divsion then the candidate is prime
blnReturnValue = True
GoTo ProcedureExit
ElseIf lngNum Mod i = 0 Then
'if we found a number that evenly divides our candidate then it is
'NOT prime
blnReturnValue = False
GoTo ProcedureExit
End If
Next i

'just in case
blnReturnValue = True

ProcedureExit:
On Error Resume Next
IsPrime = blnReturnValue
Exit Function

ProcedureError:
MsgBox Err.Source & ":" & vbCrLf & Err.Description, vbCritical, kstrProcedureName

End Function
[/code]

[size=5][italic][blue][RED]i[/RED]nfidel[/blue][/italic][/size]

[code]
\$ select * from users where clue > 0
no rows returned
[/code]

• Member Posts: 67