Swift 程序实现 nCr (r 组合)


本教程将讨论如何编写一个 Swift 程序来执行 nCr(r 组合)。

nCr 指的是 r 组合。它用于计算可能的排列,其中选择的顺序无关紧要。或者我们可以说 nCr 用于从 n 个项目的集合中选择 r 个项目,其中项目的顺序不考虑。

公式

以下是 nCr 的公式

nCr = (n!)/(r! * (n - r)!)

下面是相同内容的演示 -

假设我们输入以下输入。

N = 5
R = 3

以下是所需的输出。

nCr = 10

算法

算法解释如下 -

  • 步骤 1 - 创建一个函数来查找数字的阶乘。

  • 步骤 2 - 创建一个名为 combination() 的函数来计算 nCr。

  • 步骤 3 - 使用两个参数调用 combination 函数,即 N 和 R。此处 N 和 R 的值可以是预定义的或用户定义的。

  • 步骤 4 - 显示最终输出。

示例 1

以下程序演示了如何执行 nCr(r 组合)

import Foundation import Glibc func factorial(N: Int) -> Int{ var output = 1 if (N > 1) { for j in 1...N{ output *= j } } return output } func combination(N: Int, R: Int) -> Int{ return factorial(N: N)/(factorial(N:R) * factorial(N:(N - R))) } print("Result of nCr is", combination(N: 5, R: 3))

输出

Result of nCr is 10

在上面的代码中,我们首先创建一个名为 factorial() 的函数。此函数接受 1 个参数并返回给定数字的阶乘。现在我们创建另一个名为 combination() 的函数,它接受两个参数并使用数学公式返回组合 -

func combination(N: Int, R: Int) -> Int{
    return factorial(N: N)/(factorial(N:R) * factorial(N:(N - R)))
}

在这里,我们使用 factorial() 函数查找数字的阶乘。现在我们使用两个参数 N = 5 和 R = 3 调用 combination() 函数,并显示 nCr 的最终值,即 10。

示例 2

以下程序演示了如何使用用户输入执行 nCr(r 组合)

import Foundation import Glibc func factorial(N: Int) -> Int{ var output = 1 if (N > 1) { for j in 1...N{ output *= j } } return output } func combination(N: Int, R: Int) -> Int{ return factorial(N: N)/(factorial(N:R) * factorial(N:(N - R))) } print("Enter the value of N- ") var num1 = Int(readLine()!)! print(num1) print("Enter the value of r-")
var num2 = Int(readLine()!)! print(num2) print("Result of nCr is", combination(N: num1, R: num2))

STDIN 输入

Enter the value of N- 
9
Enter the value of r-
4

输出

Result of nCr is 126

在上面的代码中,我们首先创建一个名为 factorial() 的函数。此函数接受 1 个参数并返回给定数字的阶乘。现在我们创建另一个名为 combination() 的函数,它接受两个参数并使用数学公式返回组合 -

func combination(N: Int, R: Int) -> Int{
   return factorial(N: N)/(factorial(N:R) * factorial(N:(N - R)))
}

在这里,我们使用 factorial() 函数查找数字的阶乘。现在我们使用 readLine() 函数从用户那里获取 N 和 R 的值,即 9 和 4。现在我们调用 combination() 函数并将这两个变量(即 N 和 R)作为参数传递,并显示最终结果,即 126。

更新于: 2022 年 8 月 5 日

243 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.