Find the factorial of a number, using Recursion

29 Nov

Let’s say someone asked you to write a method that can find the factorial of a number. I’ll show you how. And then I’ll show you how to do it recursively. Remember recursion?

But first, see the definition of Factorial from wikipedia, for those of you who didn’t do math in school.

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,

5! = 1 x 2 x 3 x 4 x 5 = 120

and
$6 ! = 1 \times 2 \times 3 \times 4 \times 5 \times 6 = 720 \$

Standard Way

So here is the method. It takes a number and returns its factorial. This is a standard way of doing it, or you can refactor the code and make it more concise

Public Function Factorials(Byval n As Integer) As Integer

if n<1 Then return 1
Dim res As integer = 1
For i As Integer = 1 to n
res*= i
Next i
Return res
End Function


Using Recurcion to find the factorial.
So imagine that you have to use recurcion to get the same results. Not difficult at all. You just change the code a little bit and have the method call itself. See the code below.

Public Function Factorials(Byval n As Integer) As Integer

If n<1 Then
Return 1
Else
Return (n * Factorials(n-1))
End If
End Function


So that is it. Both methods work fine and return the same results. Another little bit on recursion.
Till next time, yours truly.