Prime Numbers - Programmers Heaven

#### Howdy, Stranger!

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

#### Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

# Prime Numbers

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

• Posts: 2,444Member
: 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

• Posts: 2,900Member
: 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]

• Posts: 67Member