用 C 程式語言求 nCr 和 nPr。
在 C 程式語言中,nCr 被稱為組合。nCr 是從一組 n 個物件中選擇 r 個物件,其中物件的順序無關緊要。
nPr 被稱為**排列**。nPr 是從一組 'n' 個物件中排列 'r' 個物件,這些物件應按順序排列。
排列和組合公式
以下是在 C 語言中求給定數字的排列和組合的公式:
- nCr = n!/(r!*(n-r)!)
- nPr = n!/(n-r)!。
用於求 nCr 的邏輯如下:
result = factorial(n)/(factorial(r)*factorial(n-r));
用於求 nPr 的邏輯如下:
result = factorial(n)/factorial(n-r);
示例
以下是用 C 語言求給定數字的排列和組合的程式:
#include <stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
int main(){
int n, r;
long ncr, npr;
printf("Enter the value of n and r
");
scanf("%d%d",&n,&r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
printf("%dC%d = %ld
", n, r, ncr);
printf("%dP%d = %ld
", n, r, npr);
return 0;
}
long find_ncr(int n, int r) {
long result;
result = factorial(n)/(factorial(r)*factorial(n-r));
return result;
}
long find_npr(int n, int r) {
long result;
result = factorial(n)/factorial(n-r);
return result;
}
long factorial(int n) {
int c;
long result = 1;
for (c = 1; c <= n; c++)
result = result*c;
return result;
}輸出
執行上述程式後,它將生成以下輸出:
Enter the value of n and r 5 2 5C2 = 10 5P2 = 20
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP