C++ Program to Find Permutation (nPr) and Combination (nCr)

nCr nPr

C++ programs to find the value of $nPr$ and $nCr$ have been shown here. $nPr$, $nCr$ are referred as the permutation and combination respectively. The formula to find $nPr$ and $nCr$ are given below.


 $nPr = \frac{n!}{(n-r)!}$


 $nCr = \frac{n!}{(n-r)! \cdot r!}$


Example:

Suppose $n = 5$ and $r = 3$


$5P3 = \frac{5!}{(5-3)!} = \frac{5!}{2!} = \frac{120}{2} = 60$


$5C3 = \frac{5!}{(5-3)!\cdot3!} = \frac{5!}{2!\cdot3!} = \frac{120}{12} = 10$







1. Program & output to find the value of nCr and nPr




1.1. C++ Program & output to find the value of nCr and nPr using iteration

Code has been copied
/*******************************
       alphabetacoder.com
C++ Program to find nCr and nPr 
********************************/

#include<iostream>

using namespace std;

// function to calculate factorial
long factorial(int num) {
    // declare variables
    int i;
    long fact = 1;
    // calculate factorial
    for (i = 2; i <= num; i++)
        fact *= i;

    // return result
    return fact;
}

// function to calculate nCr
long calculate_ncr(int n, int r) {
    // return result
    return factorial(n) / (factorial(n - r) * factorial(r));
}

// function to calculate nPr
long calculate_npr(int n, int r) {
    // return result
    return factorial(n) / factorial(n - r);
}

int main() {
    // delclare variables
    int n, r;

    // take input
    cout << "Enter the value of n: ";
    cin >> n;
    cout << "Enter the value of r: ";
    cin >> r;

    // display results by calling function
    cout << n << "P" << r << " = " << calculate_npr(n, r) << endl;
    cout << n << "C" << r << " = " << calculate_ncr(n, r) << endl;

    return 0;
}

Output


Enter the value of n: 6

Enter the value of r: 3

6P3 = 120

6C3 = 20





1.2. C++ Program & output to find the value of nCr and nPr using recursion

Code has been copied
/*******************************
       alphabetacoder.com
C++ Program to find nCr and nPr 
********************************/

#include<iostream>

using namespace std;

// recursive function to calculate factorial
long factorial(int num) {
    if (num <= 1)
        return 1;

    return num * factorial(num - 1);
}

// function to calculate nCr
long calculate_ncr(int n, int r) {
    // return result
    return factorial(n) / (factorial(n - r) * factorial(r));
}

// function to calculate nPr
long calculate_npr(int n, int r) {
    // return result
    return factorial(n) / factorial(n - r);
}

int main() {
    // delclare variables
    int n, r;

    // take input
    cout << "Enter the value of n: ";
    cin >> n;
    cout << "Enter the value of r: ";
    cin >> r;

    // display results by calling function
    cout << n << "P" << r << " = " << calculate_npr(n, r) << endl;
    cout << n << "C" << r << " = " << calculate_ncr(n, r) << endl;

    return 0;
}

Output


Enter the value of n: 10

Enter the value of r: 6

10P6 = 151200

10C6 = 210