Go – Simple Factorial Program in Go Programming Language

Hello everyone, In this post, we will show you how to write a simple factorial program in the Go programming language. The example program has been tested and shared in the same post.

Go – Factorial Program

In below program, you can see it has two functions defined, the factorial() function is taking an integer as an argument and which is responsible for calculating factorial for a given number and main() function is an entry point of an application.

package main

import "fmt"

// main function
func main() {

	for a := 1; a <= 10; a++ {
		fmt.Println(a," factorial is", factorial(a))
	}
}

// function to find factorial
func factorial(number int) int {
	var result int = 1

	for i := 1; i <= number; i++ {
		result = result * i
	}

	return result
}

Go - Recursive Factorial Program

package main

import "fmt"

// main function
func main() {

	for a := 1; a <= 10; a++ {
		fmt.Println(a," factorial is", factorial(a))
	}
}

// function to find factorial
func factorial(number int) int {
	if number >= 1 {
		return number * factorial(number - 1)
	}
	return 1
}

Output

1  factorial is 1
2  factorial is 2
3  factorial is 6
4  factorial is 24
5  factorial is 120
6  factorial is 720
7  factorial is 5040
8  factorial is 40320
9  factorial is 362880
10  factorial is 3628800

References

  1. https://golang.org/doc/
  2. https://golang.org/pkg/
  3. https://golang.org/pkg/fmt/
  4. https://golang.org/pkg/fmt/#Println