Go Program to Calculate Factorial Using Recursion
func factorial(n int) int that calls itself with n-1 until it reaches 1, returning the product of all numbers from 1 to n.Examples
How to Think About It
Algorithm
Code
package main import "fmt" func factorial(n int) int { if n <= 1 { return 1 } return n * factorial(n-1) } func main() { num := 5 fmt.Printf("Factorial of %d is %d\n", num, factorial(num)) }
Dry Run
Let's trace factorial(5) through the code
Call factorial(5)
Since 5 > 1, return 5 * factorial(4)
Call factorial(4)
Since 4 > 1, return 4 * factorial(3)
Call factorial(3)
Since 3 > 1, return 3 * factorial(2)
Call factorial(2)
Since 2 > 1, return 2 * factorial(1)
Call factorial(1)
Since 1 <= 1, return 1
Calculate results back up
factorial(2) = 2 * 1 = 2 factorial(3) = 3 * 2 = 6 factorial(4) = 4 * 6 = 24 factorial(5) = 5 * 24 = 120
| Call | Return Value |
|---|---|
| factorial(1) | 1 |
| factorial(2) | 2 |
| factorial(3) | 6 |
| factorial(4) | 24 |
| factorial(5) | 120 |
Why This Works
Step 1: Base Case
The function stops calling itself when n is 1 or less, returning 1 to avoid infinite recursion.
Step 2: Recursive Call
For values greater than 1, the function calls itself with n-1, breaking the problem into smaller parts.
Step 3: Multiplying Results
Each call multiplies n by the factorial of n-1, building the final factorial value as calls return.
Alternative Approaches
package main import "fmt" func factorialIterative(n int) int { result := 1 for i := 2; i <= n; i++ { result *= i } return result } func main() { num := 5 fmt.Printf("Factorial of %d is %d\n", num, factorialIterative(num)) }
package main import "fmt" var memo = map[int]int{0:1, 1:1} func factorialMemo(n int) int { if val, ok := memo[n]; ok { return val } memo[n] = n * factorialMemo(n-1) return memo[n] } func main() { num := 5 fmt.Printf("Factorial of %d is %d\n", num, factorialMemo(num)) }
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself n times, so the time grows linearly with the input number.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to n.
Which Approach is Fastest?
The iterative approach uses constant space and is generally faster, while recursion is simpler but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, small inputs |
| Iterative | O(n) | O(1) | Large inputs, performance |
| Memoization | O(n) | O(n) | Repeated calls with same inputs |