Program to find nCr values for r in range 0 to n, in an efficient way in Python


Suppose we have to calculate nCr values many times. We can solve this very efficient way. If we store the lower values of nCr we can easily find higher values. So if we have n, we have to find list of nC0 to nCn. If answer is too large then return that modulo 10^9.

So, if the input is like n = 6, then the output will be [1, 6, 15, 20, 15, 6, 1].

To solve this, we will follow these steps −

  • items := a list with single element 1
  • for r in range 1 to n, do
    • insert floor of (last element of items * (n-r+1) /r) at the end of items
    • items[n-2] := items[n-2] mod 10^9 where n is size of items
  • return items

Example

Let us see the following implementation to get better understanding −

def solve(n):
   items = [1]
   for r in range(1,n+1):
      items.append(items[-1]*(n-r+1)//r)
      items[-2] %= 10**9
   return items

n = 6
print(solve(n))

Input

6

Output

[1, 6, 15, 20, 15, 6, 1]

Updated on: 23-Oct-2021

509 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements