Factorial in Go
In this tutorial, we will learn how to compute the factorial of a number using a loop in Go. Factorial of a number is the product of all positive integers less than or equal to that number.
What is Factorial
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!
) is calculated as 5 * 4 * 3 * 2 * 1 = 120
.
Syntax
The syntax to compute factorial using a loop in Go is:
package main
import (
"fmt"
)
// factorial computes the factorial of a given number using a loop
func factorial(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
number := 5
fmt.Printf("Factorial of %d is: %d\n", number, factorial(number))
}
Youtube Learning Video
Example 1: Computing factorial using a loop
We can create a function named factorial
to compute the factorial of a given number using a loop.
For example,
- Define a function named
factorial
that takes one parametern
of typeint
and returns anint
. - Initialize a variable
result
to 1 to store the factorial. - Use a
for
loop to iterate from 1 ton
. - In each iteration, multiply
result
by the current loop index. - Return the
result
after the loop completes. - In the main function, define a number, call
factorial
with the number, and print the result.
Go Program
package main
import (
"fmt"
)
// factorial computes the factorial of a given number using a loop
func factorial(n int) int {
result := 1
for i := 1; i <= n; i++ {
result *= i
}
return result
}
func main() {
number := 5
fmt.Printf("Factorial of %d is: %d\n", number, factorial(number))
}
Output
Factorial of 5 is: 120