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.