Question Factorial Loop

Jynx

Active member
Joined
Oct 20, 2007
Messages
44
Programming Experience
Beginner
So I need to write an application that uses 2 listbox's.
The first listbox simply loads the values 1 - 20.
The list box next to it just shows the Factorial for each number in the listbox1.
This just happens when the form loads. While trying to figure out how to do this I can do :

VB.NET:
        Dim factorial As Long = 1
        For i As Long = 1 To 20
            factorial = factorial * i
        Next i
        ListBox2.Items.Add(factorial)

This just gives me the factorial for the number 5. I can't figure out how to get it to list the factorial for 1, 2, 3, 4, & 5 in the listbox2.
 
For i As Integer = 1 To 20
ListBox2.Items.Add(Factorial(i))​
Next

Private Function Factorial(value As Integer) As Long
If value <= 1 Then
Return 1​
End If
Return value * Factorial(value - 1)​
End Function
 
Just how is 190 calls, comparisons, multiplies and subtractions better than 20 multiplies for the exact same results? A generalized solution wasn't requested.
 
I didn't know it was a challenge...
I just posted this because I've put the factorial function as Snippet and then when I wanted it's more re-usable, nothing more
 
Both methods here achieve the same result BanditSteve and Sehnsucht, and Jynx's app may have a need to calculate factorials beyond 20 sometime too, who knows.
 
No challenge intended. It was just a matter of a simple question being asked and answered and if a resource eating general solution is applied where it isn't needed, then don't use it. The OP really just had one line of code misplaced. Now try plugging 1 - 21 into either solution:) - not a general solution solution at all.
 
Back
Top