Menu Close

Go – Program to find the factorial of a number in go golang

In this article, we are going to learn about code and algorithm to find the factorial of a number in go golang. We will implement factorial of a number code using for loop and recursion.

There are many ways to find the factorial of a number in go golang.

1:) Using for loop

Algorithm:

  • Get the number as input from user
  • Run for loop from 1 to up to number
  • Calculate factorial

Code:

package main

import "fmt"

func main() {

  var n int
  
  var fact int = 1

  fmt.Print("Enter the Number: ")
  
  fmt.Scan(&n)

  if (n < 0) {
      
    fmt.Print("\nFactorial of a negative number is not possible")
    
  }

  for i := 1; i <= n; i++ {
      
    fact = fact * i
    
  }

  fmt.Printf("\nFactorial is %d", fact)
  
}

2:) Using recursion

Algorithm:

  • Get the number as input from user
  • Do recursive call to get factorial number
  • Return the factorial value

Code:

package main

import "fmt"

func factorial(n int) int {

  if (n == 1) {
      
      return 1
  }

  return n * factorial(n-1)
}

func main() {

  var n int

  fmt.Print("Enter the Number: ")
  
  fmt.Scan(&n)

  if (n < 0) {
      
    fmt.Print("\nFactorial of a negative number is not possible")

  }

  result := factorial(n)
  
  fmt.Printf("\nFactorial is %d", result)
  
}

Output:

Enter the Number:  Factorial is 120
Reference:
https://en.wikipedia.org/wiki/Factorial

To learn more about golang, please follow given below link:
https://techieindoor.com/go-lang-tutorial/
Posted in golang, golang program

Leave a Reply

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