Golang 如何执行nCr(r-combinations)
在本教程中,我们将在Golang编程语言中执行nCr(r-combinations)。nCr(r-combinations)的用例是找到可能排列的总数,其中顺序并不重要。换句话说,我们要从n个项目中选择顺序不重要的r个项目。本教程将包括两种在Golang编程语言中找到这个的方法。
解释
例如,对于n =5和r = 3
nCr = n!/ ( r!* ( n – r )!)
= 5!/ ( 3! * 2! )
= 120 / 12
= 10
算法
第1步 - 声明所有需要的变量来存储n、r、n阶乘、r阶乘和n-r阶乘。
第2步 --初始化n、r、n阶乘、r阶乘和n-r阶乘的值。
第3步 – 找到n、r和n-r的阶乘。
第4步 - 使用上述公式求出nCr。
第5步 - 打印结果。
例子
在这个例子中,我们将使用for循环查找nCr。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
func main() {
// declaring the variables to store the value of n, r and answer
var n, r, nFactorial, rFactorial, nminusrFactorial, answer int
fmt.Println("Program to find the nCr using the for loop.")
// initializing the value of n
n = 10
// initializing the value of r
r = 8
nFactorial = 1
// finding factorial of n
for i := 1; i <= n; i++ {
nFactorial = nFactorial * i
}
rFactorial = 1
// finding factorial of r
for i := 1; i <= r; i++ {
rFactorial = rFactorial * i
}
nminusrFactorial = 1
// finding factorial of n - r
for i := 1; i <= n-r; i++ {
nminusrFactorial = nminusrFactorial * i
}
// finding answer by using the formulae
answer = nFactorial / (rFactorial * nminusrFactorial)
// printing the result
fmt.Println("The value of nCr with n =", n, "and r=", r, "is", answer)
}
输出
Program to find the nCr using the for loop.
The value of nCr with n = 10 and r= 8 is 45
算法
第1步 - 声明所有需要的变量,以存储n、r、n阶乘、r阶乘和n-r阶乘。
第2步 --初始化n、r、n阶乘、r阶乘和n-r阶乘的值。
第3步 – 在单独的函数中找到n、r和n-r的阶乘。
第4步 - 使用上述公式找到nCr。
第5步 - 打印结果。
例子
在这个例子中,我们使用单独的函数来寻找n、r和n-r的阶乘。
package main
// fmt package provides the function to print anything
import (
"fmt"
)
// this is a recursive function of return type int
// which is returning the factorial of number
// passed in argument
func factorial(n int) int {
if n == 1 {
return 1
}
return factorial(n-1) * n
}
func main() {
// declaring the variables to store the value of n, r and answer
var n, r, nFactorial, rFactorial, nminusrFactorial, answer int
fmt.Println("Program to find the nCr using the separate function to find the factorial of n, r and, n-r.")
// initializing the value of n
n = 10
// initializing the value of r
r = 8
// finding factorial of n
nFactorial = factorial(n)
// finding factorial of r
rFactorial = factorial(r)
// finding factorial of n - r
nminusrFactorial = factorial(n - r)
// finding answer by using the formulae
answer = nFactorial / (rFactorial * nminusrFactorial)
// printing the result
fmt.Println("The value of nCr with n =", n, "and r=", r, "is", answer)
}
输出
Program to find the nCr using the separate function to find the factorial of n, r and, n-r.
The value of nCr with n = 10 and r= 8 is 45
结语
以上是在Golang编程语言中执行nCr(r-combinations)的两种方法。第二种方法在模块化和代码重用性方面要好得多,因为我们可以在项目的任何地方调用该函数。