You are here

C program to find ncr and npr

C program to find nCr and nPr: This code calculate nCr which is n!/(r!*(n-r)!) and nPr = n!/(n-r)!

C program to find nCr using function

  1. #include <stdio.h>
  2.  
  3. long factorial(int);
  4. long find_ncr(int, int);
  5. long find_npr(int, int);
  6.  
  7. int main()
  8. {
  9.    int n, r;
  10.    long ncr, npr;
  11.  
  12.    printf("Enter the value of n and r\n");
  13.    scanf("%d%d",&n,&r);
  14.    
  15.    ncr = find_ncr(n, r);
  16.    npr = find_npr(n, r);
  17.    
  18.    printf("%dC%d = %ld\n", n, r, ncr);
  19.    printf("%dP%d = %ld\n", n, r, npr);
  20.  
  21.    return 0;
  22. }
  23.  
  24. long find_ncr(int n, int r) {
  25.    long result;
  26.    
  27.    result = factorial(n)/(factorial(r)*factorial(n-r));
  28.    
  29.    return result;
  30. }
  31.  
  32. long find_npr(int n, int r) {
  33.    long result;
  34.    
  35.    result = factorial(n)/factorial(n-r);
  36.    
  37.    return result;
  38. }
  39.  
  40. long factorial(int n) {
  41.    int c;
  42.    long result = 1;
  43.  
  44.    for (c = 1; c <= n; c++)
  45.       result = result*c;
  46.  
  47.    return result;
  48. }

Download NCR and NPR program.

Output of program:
NCR and NPR c program

Another way to calculate nPr and nCr using functions

We use long long data type in our program to handle large numbers.

  1. #include <stdio.h>
  2. #define ll long long
  3.  
  4. void find_ncr_npr(int, int, ll*, ll*);
  5. ll find_npr(int, int);
  6. ll factorial(int);
  7.  
  8. int main() {
  9.    int n, r;
  10.    ll ncr, npr;
  11.  
  12.    printf("Input n and r\n");
  13.    scanf("%d%d", &n, &r);
  14.  
  15.    find_ncr_npr(n, r, &npr, &ncr);
  16.    
  17.    printf("%dC%d = %lld\n", n, r, ncr);
  18.    printf("%dP%d = %lld\n", n, r, npr);
  19.  
  20.    return 0;
  21. }
  22.  
  23. void find_ncr_npr(int n, int r, ll *npr, ll *ncr) {
  24.    *npr = find_npr(n, r);
  25.    *ncr = *npr/factorial(r);
  26. }
  27.  
  28. ll find_npr(int n, int r) {
  29.    ll result = 1;
  30.    int c = 1;
  31.  
  32.    while (c <= r) {
  33.       result = result * (n - r + c);
  34.       c++;
  35.    }
  36.    
  37.    return result;
  38. }
  39.  
  40. ll factorial(int n) {
  41.    int c;
  42.    ll result = 1;
  43.  
  44.    for (c = 1; c <= n; c++)
  45.       result = result*c;
  46.  
  47.    return result;
  48. }