Find Factorial of a Number using Recursion in Go



In this tutorial, we will learn how to find the factorial of a number using recursion in Go. We will cover the basic concept of factorial and implement a recursive function to perform the calculation.


What is Factorial

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and is calculated as n! = n × (n-1) × (n-2) × ... × 1. The factorial of 0 is 1.


Syntax

The syntax to find the factorial of a number using recursion in Go is:

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}


Youtube Learning Video



Example 1: Finding the factorial of a number using recursion

We can create a function to calculate the factorial of a given number using recursion.

For example,

  1. Define a function named factorial that takes one parameter n of type int.
  2. Check if n is equal to 0. If true, return 1 (base case).
  3. Otherwise, return n multiplied by the result of calling factorial with n - 1 (recursive case).
  4. In the main function, call the factorial function with a sample number and print the result.

Go Program

package main

import (
    "fmt"
)

func factorial(n int) int {
    if n == 0 {
        return 1
    }
    return n * factorial(n-1)
}

func main() {
    // Sample number
    number := 5

    // Calculate the factorial
    result := factorial(number)

    // Print the result
    fmt.Printf("Factorial of %d is %d\n", number, result)
}

Output

Factorial of 5 is 120