# Check and Generate Prime Numbers in Visual Basic

**Program Abstraction:*** This article contains two VB program. One contains the login of prime number and second one generate the prime numbers between 1 to 100.*

__Program to check whether the given number is prime number or not__

__Program to check whether the given number is prime number or not__

Prime numbers are the numbers which cannot be perfect divisible by numbers except that number and One (1). 2, 3, 5, 7, 11, 13, 17, 23, ………..

In case of 4, which can be divisible by 4. So that is why 4 is not a prime number.

In case of 3, only 3 and 1 can be perfect divisible, else we get rational numbers. That is why 3 is a prime number.

The number 1 (one) is not a prime nor a non-prime. So this program has an exception for one. (Does not consider 1).

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim check As Integer

check = 1

Dim num As Integer

num = TextBox1.Text

For i = 2 To (num – 1)

If num Mod i = 0 Then

check = 0

Exit For

End If

Next

If check = 0 Then

MessageBox.Show(“Not prime”)

Else

MessageBox.Show(“prime”)

End If

End Sub

**Program Logic: **

**
**The textbox1 accept number from user and saved on the variable ‘num’. The ‘For loop’ continuously divide the number from 2 to given number (except number, that is num – 1). While division if the modulus value (reminder after division) equals zero, then number will considered as not prime. The variable ‘check’ check the reminder whether it become zero or not. If anytime which become zero, then value of ‘check’ get value 0. At final, if the value of ‘check’ is zero. Then the given number should be non-prime else prime.

If the value of check become zero at once in a loop, then number should be non-prime, then no need to divide with more numbers. So why we used ‘Exit for’. Which escape from the ‘For’ loop.

It is only necessary to divide and check numbers up to square root of the given number, no need to divide until the given number.

For i = 2 To Math.Sqrt(num)

__VB program to find prime numbers between 1 to 100__

__VB program to find prime numbers between 1 to 100__

Here we don’t need text box, but we need a list box to display prime numbers.

Here two ‘For loop’ used. First loop iterate numbers from 1 to 100. Second loop check each number check whether it is prime or no. if it is prime, then the number will be added into the listbox.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim check As Integer

Dim num As Integer

For num = 2 To 100

check = 1

For i = 2 To Math.Sqrt(num)

If num Mod i = 0 Then

check = 0

Exit For

End If

Next

If check = 1 Then

ListBox1.Items.Add(num)

Else

check = 1

End If

Next

End Sub

## Be First to Comment