Prime Numbers

userxyz

Member
Join Date
May 2002
Location
any
Posts
2,768
How can u find prime numbers, and how to write in Visual Basic ?

Like, if u enter a number in a textfield, the code must calculate if it's a prime number, yes or no...

?
 
Option Explicit

Private Sub Command1_Click()
Dim n As Long
Dim i As Long

On Error Resume Next
n = CLng(Text1.Text)
i = 2
While (i < n) And (n / i <> n \ i)
i = i + 1
Wend

If i = n Then
MsgBox "this seam to be prime number"
Else
MsgBox "i don't think so..."
End If

End Sub

but there are so many ways to speed this up so it works nice and fast for larger numbers. (no need to test all even numbers, numbers greater than 1/2 of entered value etc.)
 
Just another variation....

Code:
Private Sub Command1_Click()
  Dim Counter As Long
  Dim Value As Long
  Dim Results As Boolean
  Value = Abs(Val(Me.Text1.Text))
  Results = True
  For Counter = 2 To Value - 1
	If Value Mod Counter = 0 Then
	  Results = False
	  Exit For
	End If
  Next Counter
  MsgBox "Prime Number Is " & Results
End Sub
 
hi

I'm study Visual Basic on my own, so it's not homework, I just hadn't any idea how to begin on this exercise. It's an exercise of www.bisonline.be

panic mode said:
precisely...:nodi:




Thanks for the code Corbis and Panic mode, I understand the code and thanks a lot, now I have a start to write it in my own way.
 
For simple loop-based prime number determination, you can save half the loop time by only checking integral divisors from 2 to ((Value/2) + 1). There are other tricks to shortcut loop-checking even further, but they will not be able to recognize all primes in a mathmatical manner.
 

Similar Topics

I have been using Windows 10 to do some long term tests on a laptop. I chose a laptop because it would die in case of a power outage. This test...
Replies
26
Views
8,492
In a PV 5310, can you format a numeric object to create comma's in the thousands position? I see no way from the properties panel.
Replies
11
Views
450
Hello everyone, friends. I need help with something. I want to read and change Bit and Byte numbers via HMI. I found a code snippet for this as...
Replies
18
Views
3,025
I'm working with a ROC800 program offline right now. Normally, you can switch your TLP view between text and numbers by making your choice under...
Replies
2
Views
849
How many motors we operate from single drive? I have 4 motors of 1hp, all motors have same function. Is it possible to run all 4 motors from...
Replies
16
Views
5,193
Back
Top Bottom