.Net Programming

Checking Prime Number in VB.Net

Logic behind the program is to check till half of the number (n/2) because it has been observed that the remainders get repeated after half of the number. Therefore, checking for remainders till n/2 is sufficient enough. The use of modulus operator(%) is important in this regard.

Related : How to find prime numbers in a given range

Language : VB.Net

Prime
[sourcecode language='vb']
Public Class Prime

Private Sub cmdPrime_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrime.Click
Dim flag As Boolean = True
Dim num As Integer = Val(txtNo.Text)
For i = 2 To num / 2
If (num Mod i = 0) Then
flag = False
Exit For
End If
Next i
If flag = False Then
MsgBox(“Not Prime”)
Else
MsgBox(“Prime”)
End If
End Sub

End Class
[/sourcecode]



Leave a Comment

Notify me of followup comments via e-mail. You can also subscribe without commenting.


WordPress - Vaibhav Kanwal