Introduction
The factorial of a number is the product of all positive integers less than or equal to that number.
Factorial is commonly denoted by the symbol “n!” where “n” is the number. For example, the factorial
of 5 is 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorial plays a significant role in mathematics, particularly in
combinatorics, probability, and algebra.
Objective
In this program, we aim to calculate the factorial of a given integer using the Go programming language.
The program will ask for user input, compute the factorial recursively, and display the result.
Go Code: Factorial Calculation
package main
import (
"fmt"
"log"
"strconv"
)
// Factorial function to calculate factorial recursively
func factorial(n int) int {
if n == 0 || n == 1 {
return 1
}
return n * factorial(n-1)
}
func main() {
// Taking user input
var input string
fmt.Print("Enter a positive integer: ")
fmt.Scanln(&input)
// Converting input to integer
num, err := strconv.Atoi(input)
if err != nil || num < 0 {
log.Fatal("Please enter a valid positive integer.")
}
// Calculating factorial
result := factorial(num)
// Outputting the result
fmt.Printf("The factorial of %d is %d\n", num, result)
}
Explanation of the Program Structure
This Go program consists of the following key parts:
- Import Statements: The program uses three packages:
fmt
for input and output,log
for error handling, andstrconv
for string-to-integer conversion. - Factorial Function: A recursive function
factorial(n int) int
that calculates the factorial of a given integer. Ifn
is 0 or 1, it returns 1 (base case); otherwise, it recursively calls itself withn-1
. - Input Handling: The program asks the user to input a positive integer and checks if the input is valid. If not, it stops execution and prints an error message.
- Main Function: This is where the input is taken, the factorial is calculated, and the result is printed to the console.
How to Run the Program
Follow these steps to run the Go program on your machine:
- Install Go from the official Go website: https://golang.org/dl/
- Create a new file, for example
factorial.go
, and copy the code provided above into that file. - Open your terminal (Command Prompt, PowerShell, or any shell) and navigate to the directory where the
factorial.go
file is saved. - Run the following command to compile and execute the Go program:
go run factorial.go
- The program will prompt you to enter a positive integer. After entering the number, it will calculate and display the factorial.