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 integer n.
    • If n is 0, it returns 1 since 0! = 1.
    • Otherwise, it returns n multiplied by the factorial of n-1.
  • 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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)