This is a program I have to submit in a few hours that checks whether numbers are prime or not. I have it to the point where is tells me the correct answer, but for some reason my loop is infinite. I'm just in an intro class and I was wondering if I could get some help.

Thanks a lot.

Public Class Form1

    Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
        Dim userInput As Long

        userInput = tbInput.Text

        Do

            If IsPrime(userInput) = True Then
                MessageBox.Show(userInput & " Is a prime number")
            ElseIf IsPrime(userInput) = False Then
                MessageBox.Show(userInput & " Is not a prime number")
            End If

        Loop

    End Sub


    Function IsPrime(ByVal checkValue As Long) As Boolean

        IsPrime = True

        For testValue = 2 To CLng(Math.Sqrt(checkValue))
            If checkValue Mod testValue = 0 Then
                IsPrime = False
                Exit Function
            End If
        Next

    End Function

End Class

Your "If..." statement on line 10 has no condition for breaking out of the loop. You don't even really need a "Do...Loop" here. It's an event-driven program and this event procedure has a single number to process. Your testing loop is inside the IsPrime function (where it is appropriate).

Edited 5 Years Ago by BitBlt: n/a

This article has been dead for over six months. Start a new discussion instead.