首頁  >  文章  >  後端開發  >  C程式找到nCr和nPr

C程式找到nCr和nPr

WBOY
WBOY轉載
2023-08-28 23:05:121028瀏覽

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);

Example

以下是用來找到給定數字的排列和組合的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</p><p>");
   scanf("%d%d",&n,&r);
   ncr = find_ncr(n, r);
   npr = find_npr(n, r);
   printf("%dC%d = %ld</p><p>", n, r, ncr);
   printf("%dP%d = %ld</p><p>", 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

以上是C程式找到nCr和nPr的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除