How to calculate the factorial of a number in Go?

To calculate the factorial of a number in Go, you can use a recursive function or a loop. Here's an example of both approaches:

  1. Recursive Approach:
func factorialRecursive(n int) int { if n == 0 { return 1 } return n * factorialRecursive(n-1) } func main() { n := 5 result := factorialRecursive(n) fmt.Printf("The factorial of %d is %d\n", n, result) }
  1. Loop Approach:
func factorialLoop(n int) int { result := 1 for i := 1; i <= n; i++ { result *= i } return result } func main() { n := 5 result := factorialLoop(n) fmt.Printf("The factorial of %d is %d\n", n, result) }

Both approaches will yield the same result. The recursive approach uses a base case to terminate the recursion when n reaches 0, and the loop approach calculates the factorial by multiplying the numbers from 1 to n.