# Program to calculate value of nCr using Recursion

• Last Updated : 10 Feb, 2022

Given two numbers N and r, find the value of NCr using recursion

Examples:

Input: N = 5, r = 2
Output: 10
Explanation: The value of 5C2 is 10

Input: N = 3, r = 1
Output: 3

Approach: The idea is simply based on the below formula.

NCr = N! / (r! * (N-r)!)
Also,
NCr-1 = N! / ( (r-1)! * (N – (r-1))! )

Hence,

• NCr * r! * (N – r)! = NCr-1  * (r-1)! * (N – (r-1))!
• NCr * r * (N-r)! = NCr-1  * (N-r+1)!                          [eliminating (r – 1)! from both side]
• NCr * r = nCr-1  * (N-r+1)

Therefore,

NCr = NCr-1 * (N-r+1) / r

Below is the implementation of the above approach:

## C++

 `// C++ code to implement above approach``#include ``using` `namespace` `std;` `// Function to calculate the value of nCr``// using recursion``int` `nCr(``int` `N, ``int` `r)``{``    ``int` `res = 0;``    ``if` `(r == 0) {``        ``return` `1;``    ``}``    ``else` `{``        ``res = nCr(N, r - 1)``              ``* (N - r + 1) / r;``    ``}``    ``return` `res;``}` `// Driver code``int` `main()``{``    ``int` `N = 5, r = 3;``    ``cout << nCr(N, r);``    ``return` `0;``}`

## Java

 `// Java code for the above approach``import` `java.io.*;``class` `GFG {` `  ``// Function to calculate the value of nCr``  ``// using recursion``  ``static` `int` `nCr(``int` `N, ``int` `r)``  ``{``    ``int` `res = ``0``;``    ``if` `(r == ``0``) {``      ``return` `1``;``    ``}``    ``else` `{``      ``res = nCr(N, r - ``1``) * (N - r + ``1``) / r;``    ``}``    ``return` `res;``  ``}` `  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `N = ``5``, r = ``3``;` `    ``System.out.println(nCr(N, r));``  ``}``}` `// This code is contributed by Potta Lokesh`

## Python3

 `# Python code to implement above approach` `# Function to calculate the value Of nCr``# using recursion``def` `nCr(N, r):``    ``res ``=` `0``    ``if``(r ``=``=` `0``):``        ``return` `1``    ``else``:``        ``res ``=` `nCr(N, r``-``1``)``*` `(N``-``r ``+` `1``) ``/` `r``    ``return` `res`  `# Driver code``if` `__name__ ``=``=` `"__main__"``:``    ``N ``=` `5``    ``r ``=` `3``    ``print``(``int``(nCr(N, r)))`

## C#

 `using` `System;` `public` `class` `GFG{` `  ``// Function to calculate the value of nCr``  ``// using recursion``  ``static` `int` `nCr(``int` `N, ``int` `r)``  ``{``    ``int` `res = 0;``    ``if` `(r == 0) {``      ``return` `1;``    ``}``    ``else` `{``      ``res = nCr(N, r - 1)``        ``* (N - r + 1) / r;``    ``}``    ``return` `res;``  ``}` `  ``// Driver code``  ``static` `public` `void` `Main (){` `    ``int` `N = 5, r = 3;``    ``Console.WriteLine(nCr(N, r));``  ``}``}` `// This code is contributed by hrithikgarg03188.`

## Javascript

 ``

Output

`10`

Time Complexity: O(N!)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up