Calculate nCr using Pascal’s Triangle

A useful application of Pascal’s triangle is the calculation of combinations. The formula to find nCr is n! / r! * (n – r)! which is also the formula for a cell of Pascal’s triangle.

Input: n = 5, r = 3
Output: 10
n! / r! * (n – r)! = 5! / 3! * (2!) = 120 / 12 = 10

Input: n = 7, r = 2
Output: 21



Approach: The idea is to store the Pascal’s triangle in a matrix then the value of nCr will be the value of the cell at nth row and rth column.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Initialize the matrix with 0
l = [[0 for i in range(1001)] for j in range(1001)]
  
def initialize():
      
    # 0C0 = 1
    l[0][0] = 1
    for i in range(1, 1001):
          
        # Set every nCr = 1 where r = 0
        l[i][0] = 1
        for j in range(1, i + 1):
              
            # Value for the current cell of Pascal's triangle
            l[i][j] = (l[i - 1][j - 1] + l[i - 1][j])
  
# Function to return the value of nCr
def nCr(n, r):
      
    # Build the Pascal's triangle
    initialize()
      
    # Return nCr
    return l[n][r]
  
# Driver code
n = 8
r = 3
print(nCr(n, r))

chevron_right


Output:

56


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.