Search code examples
vb.netfunctionprimesbasic

Visual Basic: How can i display the prime numbers between 1 and the inputted number


Hello everyone so i'm trying to find the prime numbers of any input. I want them to be in a listbox and the input in a text box. I would like to use two arguments but i don't know how to. this is the code i have i need dire help. I am not the best at visual basic i just need some guidance. My code isn't working but display a drop down box when i press display.

Public Class Form1
    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click

        Dim prim As Integer
        Dim test As Integer
        Dim imPrime As Boolean = False
        prim = CInt(txtNum.Text)
        test = prim

        If prim = 1 Then
            imPrime = False
            MessageBox.Show("Enter a number greater than one please")
        Else
            Do While prim >= 2
                For i As Integer = 2 To prim
                    If prim Mod i = 0 Then
                        imPrime = False
                        Exit For
                    Else
                        imPrime = True
                        lstPrime.Items.Add(prim)
                    End If
                Next
            Loop
        End If
        If imPrime = True Then
            lstPrime.Items.Add(prim)
        End If

    End Sub
End Class

Solution

  • I think the while loop is not working as you intend. You need two loops, the first one counting up to the possible prime, and an inner one counting up to the counter in the outer loop.

    You can find examples everywhere... here's one implemented in C#, but since your question was specifically about a listbox, I've translated it to VB.

    Public Class Form1
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            calculatePrimes()
        End Sub
    
        Private Sub calculatePrimes()
    
            Dim prim As Integer
            Dim count As Integer = 0
    
            prim = CInt(Me.TextBox1.Text)
            If prim < 3 Then
                MsgBox("Please enter a bigger number")
                Return
            End If
    
            Me.ListBox1.Items.Clear()
    
            For i As Integer = 1 To prim
                Dim isPrime As Boolean = True
                For j As Integer = 2 To i
                    If (i Mod j <> 0) Then count = count + 1
                Next
                If count = (i - 2) Then Me.ListBox1.Items.Add(i)
                count = 0
            Next
    
        End Sub
    End Class
    

    (This assumes you have a textbox for input called TextBox1 and a listbox for display called ListBox1)