在 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

更新于: 2019-09-23

387 次浏览

启动你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.