How to calculate permutations and combinations in Go?

In Go, you can calculate permutations and combinations using combinatorial formulas and loops. Here are the steps to calculate permutations and combinations in Go:

  1. Import the math package to access mathematical functions:
import ( "fmt" "math" )
  1. Define a function to calculate the factorial of a number. This will be used in both permutations and combinations calculations:
func factorial(n int) int { if n == 0 { return 1 } return n * factorial(n-1) }
  1. Calculate permutations by defining a function that takes two arguments, n and r (where n is the total number of elements and r is the number of elements in each permutation):
func permutations(n, r int) int { return factorial(n) / factorial(n-r) }
  1. Calculate combinations by defining a similar function that takes n and r as arguments:
func combinations(n, r int) int { return factorial(n) / (factorial(r) * factorial(n-r)) }
  1. Provide the inputs and call the functions to calculate permutations and combinations:
func main() { n := 5 // Total number of elements r := 3 // Number of elements in each permutation or combination fmt.Println("Permutations:", permutations(n, r)) fmt.Println("Combinations:", combinations(n, r)) }

In the above example, n is set to 5 and r is set to 3. The output will be:

Permutations: 60 Combinations: 10

These calculations are based on the formulas: nPr = n! / (n-r)! for permutations and nCr = n! / (r! * (n-r)!) for combinations.