Factorial Calculation in Go
This program calculates the factorial of a given number using the Go programming language.
What is a 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 defined as:
n! = n * (n-1) * (n-2) * ... * 1
For example, 5! = 5 * 4 * 3 * 2 * 1 = 120
.
Go Program to Calculate Factorial
// Package main implements a simple program to calculate the factorial of a given number.
package main
import (
"fmt"
)
// factorial function computes the factorial of a given non-negative integer n.
// If n is 0, it returns 1 because 0! is defined to be 1.
// It returns the factorial of n otherwise.
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial(n-1)
}
// main function is the entry point of the program.
// It prompts the user to enter a number and calculates its factorial.
func main() {
var num int
fmt.Print("Enter a number to calculate its factorial: ")
fmt.Scan(&num)
if num < 0 {
fmt.Println("Factorial is not defined for negative numbers.")
} else {
result := factorial(num)
fmt.Printf("The factorial of %d is %d.\n", num, result)
}
}
Explanation
package main
: Defines the main package of the Go program.import "fmt"
: Imports the fmt package for formatted I/O.func factorial(n int) int
: Defines a recursive function to calculate the factorial of a non-negative integern
.- If
n
is 0, it returns 1 since0! = 1
. - Otherwise, it returns
n
multiplied by the factorial ofn-1
.
- If
func main()
: The main function, which is the entry point of the program.- Prompts the user to enter a number.
- Reads the input number.
- If the number is negative, it prints an error message since factorials are not defined for negative numbers.
- If the number is non-negative, it calculates the factorial by calling the
factorial
function and prints the result.