Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program find nCr and nPr.
In C programming language, nCr is referred as the combination. nCr is the selection of r objects from a set of n objects, where the order of objects does not matter.
nPr is referred as the permutation. nPr is arrangement of 'r' objects from a set of 'n' objects, which should be in an order or sequence.
Syntax
nCr = n! / (r! * (n-r)!) nPr = n! / (n-r)!
Permutations and Combinations Formulas
The formulas to find the permutation and combination of given numbers in C language are given below −
- nCr = n!/(r!*(n-r)!) − Combination formula
- nPr = n!/(n-r)! − Permutation formula
The logic used to find nCr is as follows −
result = factorial(n)/(factorial(r)*factorial(n-r));
The logic used to find nPr is as follows −
result = factorial(n)/factorial(n-r);
Example
Following is the C program to find the permutation and combination of given numbers −
#include <stdio.h>
long factorial(int);
long find_ncr(int, int);
long find_npr(int, int);
int main() {
int n = 5, r = 2;
long ncr, npr;
printf("For n = %d and r = %d<br>", n, r);
ncr = find_ncr(n, r);
npr = find_npr(n, r);
printf("%dC%d = %ld<br>", n, r, ncr);
printf("%dP%d = %ld<br>", 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 the above program is executed, it produces the following output −
For n = 5 and r = 2 5C2 = 10 5P2 = 20
Key Points
- Combinations (nCr) count selections where order doesn't matter
- Permutations (nPr) count arrangements where order matters
- For the same n and r values, nPr ? nCr always holds true
- The factorial function is the building block for both calculations
Conclusion
The nCr and nPr calculations are fundamental mathematical operations in combinatorics. Using factorial functions, we can efficiently compute both permutations and combinations for any valid set of n and r values in C programming.
