Home  >  Article  >  Backend Development  >  C program to find nCr and nPr

C program to find nCr and nPr

WBOY
WBOYforward
2023-08-28 23:05:121028browse

C program to find nCr and nPr

In the C programming language, nCr is called combination. nCr selects r objects from a collection of n objects, where the order of the objects does not matter.

nPr is called arrangement. nPr is an arrangement of "r" objects out of a set of "n" objects that should be arranged in order or sequence.

Permutation and combination formula

The formula for permutation and the combination of given numbers in C language are as follows-

  • nCr = n!/(r!*( n-r)!)
  • nPr = n!/(n-r)!.

The logic to find nCr is as follows-

result = factorial(n)/(factorial(r)*factorial(n-r));

The logic to find nPr is as follows-

result = factorial(n)/factorial(n-r);

Example

The following is a C program for finding permutations and combinations of given numbers −

#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;
}

Output

When executing the above program, the following is produced Output-

Enter the value of n and r
5 2
5C2 = 10
5P2 = 20

The above is the detailed content of C program to find nCr and nPr. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete