在 C 程式中計算 nPr 值的程式
對於 n P r(其中 P 代表排列,n 表示總數,r 表示排列),任務是計算 nPr 的值。
排列是按順序或按序排列資料。排列和組合的不同之處是,排列是排列的過程,而組合是給定集合中元素選擇的過程。
排列的公式為:
nPr = (n!)/(n-r)!
示例
Input-: n=5 r=2 Output-: 20
演算法
Start Step 1 -> declare function to calculate value of nPr int cal_n(int n) IF n <=1 Return 1 End return n*cal_n(n-1) Step 2 -> Declare function to calculate the final npr int nPr(int n, int r) return cal_n(n)/cal_n(n-r) Step 3 -> In main() Declare variables as int n=5, r=2 Print nPr(n, r) Stop
示例
#include<stdio.h>
//function to calculate the factorial for npr
int cal_n(int n){
if (n <= 1)
return 1;
return n*cal_n(n-1);
}
//function to calculate the final npr
int nPr(int n, int r){
return cal_n(n)/cal_n(n-r);
}
int main(){
int n=5, r=2;
printf("value of %dP%d is %d", n, r, nPr(n, r));
return 0;
}輸出
value of 5P2 is 20
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP