Go Program to find NCR Factorial of a Number

Write a Go Program to find NCR Factorial of a Number using Functions. The math formula to calculate the NCR factorial is: First, we created a function (func factorialCal(number int)) that returns the given number factorial. Next, we call this function by passing n and r values.

package main

import "fmt"

func factorialCal(number int) int {
    factorial := 1
    for i := 1; i <= number; i++ {
        factorial = factorial * i
    }
    return factorial
}
func main() {

    var ncr, n, r int

    fmt.Print("Enter any N and R Values = ")
    fmt.Scanln(&n, &r)

    ncr = factorialCal(n) / (factorialCal(r) * factorialCal(n-r))

    fmt.Println("The NCR Factorial = ", ncr)
}
SureshMac:GoExamples suresh$ go run ncrFactorial1.go
Enter any N and R Values = 6 2
The NCR Factorial =  15
SureshMac:GoExamples suresh$ go run ncrFactorial1.go
Enter any N and R Values = 10 8 
The NCR Factorial =  45

Go Program to find NCR Factorial of a Number using Recursion

In this Golang program, we recursively call the factorialCal(number) function with the updated number.

package main

import "fmt"

func factorialCal(number int) int {
    if number == 0 || number == 1 {
        return 1
    }
    return number * factorialCal(number-1)
}
func main() {

    var ncr, n, r int

    fmt.Print("Enter any N and R Values = ")
    fmt.Scanln(&n, &r)

    ncr = factorialCal(n) / (factorialCal(r) * factorialCal(n-r))

    fmt.Println("The NCR Factorial = ", ncr)
}
Golang Program to Calculate NCR Factorial of a Number 2

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.