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) }