1. ## finding prime numbers?

Ive made a program in vb to check to see if a number is a prime number, i was wondering what people thought was the best and fastest way to find the prime number at the moment i have:
Dim prime As Double
Dim temp As Double
Dim current As Double
Dim root As Double
Private Sub Command1_Click()
prime = Text1.Text
If prime = 1 Or prime = 2 Then
MsgBox "error"
Exit Sub
End If
current = 2
root = Sqr(prime) + 1
Do
temp = prime Mod current
If temp = 0 Then
MsgBox "not a prime"
Exit Sub
End If
current = current + 1
Loop Until current = root
MsgBox "prime"
End Sub
Has any one got any ideas?
thanx trials

2. Hmm... interesting one. Right off the bat I would increment current by 2 (current=current+2). Any number above 2 that is even will not be prime (because it's divisible by 2).

For example... square of 65 = 8.06...
If 65 mod 2 isn't one, then 65 mod 4/6/8 will also not be true.
First set current to 2, run it once, increment it by one (so it is now 3), and THEN enter the loop where it will increment by 2s (5,7,9,etc).

Good Luck.

for some reason I feel like making it clearer... here goes....
also notice another change: loop until current > root (it most likely wont be equal, and now you don't need to add 1 to the root like you have)

Dim prime As Double
Dim temp As Double
Dim current As Double
Dim root As Double
Private Sub Command1_Click()
prime = Text1.Text
If prime = 1 Or prime = 2 Then
MsgBox "error"
Exit Sub
End If

root = Sqr(prime)

'Check if even
temp = prime Mod 2
If temp = 0 Then
MsgBox "not a prime"
Exit Sub

current = 3
Do
temp = prime Mod current
If temp = 0 Then
MsgBox "not a prime"
Exit Sub
End If
current = current + 2
Loop Until current > root
MsgBox "prime"
End Sub

3. I know this is not in VB, but, you can probably convert it over somehow. It is by far the fastest way to calculate prime numbers that I've ever seen...

http://www.cpp-home.com/contests/25/code.cpp

Have fun!

4. There are far easier ways to check for primality than simply dividing by all possible divisors. While this would work for small numbers it would take eons. Currently your program will still test for divisibilty by 15 after nondivisibilty by 5 has been verified. Try a web search for "Fermat's Little Theorem" and/or "Primality Tests" and you should find some help there.

5. thanx for your help everyone

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•