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.
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.
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)
}
We can create a function to calculate the factorial of a given number using recursion.
For example,
factorial
that takes one parameter n
of type int
.n
is equal to 0. If true, return 1 (base case).n
multiplied by the result of calling factorial
with n - 1
(recursive case).factorial
function with a sample number and print the result.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)
}
Factorial of 5 is 120