Factors Finder

 

I have been answering questions pertaining to Visual Basic under the Yahoo! Answer section lately. So far I have three answers chosen as the best answers. Today I answered  another VB question  that goes like this "

How can you write a program that will ask the user to enter a number and display all the factors of the number?

 Below is the solution for the above question:

 

Private Sub Command1_Click()
Dim N, x As Integer
N = Val(Text1.Text)
For x = 2 To N - 1
If N Mod x = 0 Then
List1.AddItem (x)
End If
Next

List1.AddItem (N)


End Sub

Private Sub Command2_Click()
List1.Clear

End Sub


 

Explanation

     I use the simple logic that a number is divisible by all its factors. However, you need to tell Visual Basic how to identify factors from non factors. In order to do this , I use the fact that the remainder after a number is divided by its factor is zero. In Visual Basic, you can use the MOD operator, which compute the value of the remainder after a number is divided by an integer. The format is  N Mod x.

    With those logics in mind, I used a For....Next Loop to evaluate all the remainders for all the divisors of N smaller than N. If the remainder is zero, then the divisor x is added to the list box. In this way, I am able to compute all the factors.

 

The run time screen shot

 

 

 

 

 

 

 [Back to VBToday]