Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find nCr values for r in range 0 to n, in an efficient way in Python
Computing binomial coefficients nCr for all values of r from 0 to n can be done efficiently using Pascal's triangle properties. Instead of calculating each nCr independently, we can use the recurrence relation: nCr = nC(r-1) × (n-r+1) / r.
This approach builds the coefficients incrementally, making it much faster than computing each combination separately.
Problem Statement
Given n, find all nCr values where r ranges from 0 to n. If any result exceeds 10^9, return it modulo 10^9.
For example, if n = 6, the output should be [1, 6, 15, 20, 15, 6, 1] representing 6C0, 6C1, 6C2, ..., 6C6.
Algorithm
The solution follows these steps:
- Start with coefficients = [1] (representing nC0 = 1)
- For each r from 1 to n:
- Calculate nCr = nC(r-1) × (n-r+1) / r
- Apply modulo 10^9 to keep numbers manageable
- Append the result to coefficients list
- Return the complete list
Implementation
def solve(n):
coefficients = [1] # Start with nC0 = 1
for r in range(1, n + 1):
# Use recurrence: nCr = nC(r-1) * (n-r+1) / r
next_coeff = coefficients[-1] * (n - r + 1) // r
coefficients.append(next_coeff)
# Apply modulo to previous element to prevent overflow
coefficients[-2] %= 10**9
return coefficients
# Test with n = 6
n = 6
result = solve(n)
print(f"nCr values for n = {n}: {result}")
nCr values for n = 6: [1, 6, 15, 20, 15, 6, 1]
How It Works
The algorithm leverages the mathematical relationship between consecutive binomial coefficients:
# Example walkthrough for n = 4
def solve_with_steps(n):
coefficients = [1]
print(f"Initial: {coefficients}")
for r in range(1, n + 1):
prev_coeff = coefficients[-1]
next_coeff = prev_coeff * (n - r + 1) // r
coefficients.append(next_coeff)
print(f"r={r}: {prev_coeff} × ({n}-{r}+1) ÷ {r} = {next_coeff}")
print(f"Current list: {coefficients}")
return coefficients
result = solve_with_steps(4)
Initial: [1] r=1: 1 × (4-1+1) ÷ 1 = 4 Current list: [1, 4] r=2: 4 × (4-2+1) ÷ 2 = 6 Current list: [1, 4, 6] r=3: 6 × (4-3+1) ÷ 3 = 4 Current list: [1, 4, 6, 4] r=4: 4 × (4-4+1) ÷ 4 = 1 Current list: [1, 4, 6, 4, 1]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Direct Calculation | O(n²) | O(n) | Single nCr values |
| Recurrence Relation | O(n) | O(n) | All nCr for fixed n |
Conclusion
Using the recurrence relation nCr = nC(r-1) × (n-r+1) / r provides an efficient O(n) solution for computing all binomial coefficients. This approach is ideal when you need multiple nCr values for the same n.
