Understanding Recursion with Factorials
Recursion can simplify complex problems by defining a base case and a recursive step. One common example is computing the factorial of a number. The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. For example:- Factorial of 5:
5 × 4 × 3 × 2 × 1 = 120 - Factorial of 3:
3 × 2 × 1 = 6
In the factorial function, the base case is defined when n equals 0, because 0! is defined as 1.
Recursive Factorial Implementation in Go
Below is the complete Go code that implements the factorial calculation using recursion. The function namedfactorial takes an integer as input and returns its factorial. The recursion continues until it reaches the base case where n equals 0.
How the Recursive Function Works
When the program is executed, the following steps occur:- The
mainfunction sets the value of n to 5 and callsfactorial(5). - Since 5 is not 0,
factorial(5)returns 5 multiplied byfactorial(4). - The function continues to call itself:
factorial(4)returns 4 multiplied byfactorial(3).factorial(3)returns 3 multiplied byfactorial(2).factorial(2)returns 2 multiplied byfactorial(1).factorial(1)returns 1 multiplied byfactorial(0).
- Once
factorial(0)is reached, the base case is met and the function returns 1. - The recursive calls then resolve in reverse order:
factorial(1)becomes 1 × 1 = 1.factorial(2)becomes 2 × 1 = 2.factorial(3)becomes 3 × 2 = 6.factorial(4)becomes 4 × 6 = 24.factorial(5)becomes 5 × 24 = 120.
- Finally, the
mainfunction prints:
Factorial of 5 is: 120
Each recursive call reduces the problem size until the simplest case (n = 0) is reached, after which the results are combined to form the final output.