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

C program to find nCr and nPr

WBOY
Release: 2023-08-28 23:05:12
forward
1120 people have browsed it

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));
Copy after login

The logic to find nPr is as follows-

result = factorial(n)/factorial(n-r);
Copy after login

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;
}
Copy after login

Output

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

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

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template