How
to Determine the Factors of a Specified Number in Visual Basic Code
Tested with VB6
Courtesy of Marshall Ellis
A factor of a number is a number that when multiplied with another
factor of the same number will result in the number. It sounds more
confusing than it is. For instance, factors of 9 are 1, 3 and 9.
Factors of 5 are 1 and 5. Factors of 20 are 1, 2, 4, 5, 10 and 20.
Determining factors is related to detecting Prime Numbers, as a prime
is any number with factors of only 1 and itself.
So how do we tell VB to list the factors of a number? Sounds tough!
It's really quite easy, using the MOD function modular division
and a bit of logic.
Where regular division concerns itself with getting the absolute result
down to decimal places, modular division gives you the remainder if
you stop dividing before getting to decimals. For instance:
Regular division 5/2 = 2.5
Modular division 5/2 = 2 with a remainder of 1, or 5 Mod 2 = 1
Any number that is a factor of a specified number will give a Mod result
of 0, because it will divide evenly. Taking the number 6 as an example:
6 mod 1 = 0
6 mod 2 = 0
6 mod 3 = 0
6 mod 4 = 2
6 mod 5 = 1
6 mod 6 = 0
Thus factors of 6 are 1, 2, 3, and 6. By now you will probably see where
I am going with this, and what the code might look like. So without
further dull preliminary explanation, on to the sample code...
1 Create a new standard VB project.
2 On the form place a textbox, a command button and a listbox.
3 Set the text property of the textbox to "1" simply
to avoid it ever evaluating to zero without trying. We will concern
ourselves here only with positive numbers 1 and greater. I'll leave
generating factors of negative numbers as an exercise for the reader.
Obviously you should always code or error-trap to account for
inappropriate input, which in a minor way has been done below.
4 In the Click event of the command button place the following
code:
'Get
the number we want to test from the textbox
Dim
lngNumber
As Long
lngNumber = Text1.Text
'Clear
the listbox of anything that might remain from prior results
List1.Clear
'If
the number isn't a positive integer, go no further
If
lngNumber < 0
Then Exit Sub
'Now
loop through 1 to the specified number
For
i = 1
To
lngNumber
If
lngNumber
Mod
i = 0
Then
'Mod is 0 so the number
is evenly divisible _
by i, making the current i a factor
lstFactor.AddItem i
End If
Next
5 Run the program, enter a number in the textbox and test.
Note that the code could also be placed in a routine callable from
anywhere it might be needed in a program.
|