Skip to content

Commit d3a9471

Browse files
Merge pull request matthewsamuel95#692 from MatheusMiranda/master
Add calculation of binomial coefficients
2 parents 972f505 + 6f91788 commit d3a9471

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Complexity: O(n^2)
2+
# Computes the lines of Pascal's triangle.
3+
# Pascal's triangle gives us result of binom(n,p), which is equivalent to combination(n,p).
4+
5+
import fileinput
6+
7+
binomial_coefficients = []
8+
line = []
9+
line.append(1)
10+
binomial_coefficients.append(line)
11+
12+
# Element at line x and column y(binom[x][y]) of Pascal's triangle can be calculated as (binom[x-1][y] + binom[x-1][y-1]).
13+
def precomp(n):
14+
for i in range(1,n):
15+
line = []
16+
line.append(1)
17+
18+
for j in range(1,i):
19+
line.append(binomial_coefficients[i - 1][j] + binomial_coefficients[i - 1][j - 1])
20+
21+
line.append(1)
22+
23+
binomial_coefficients.append(line)
24+
25+
precomp(40)
26+
27+
for line in fileinput.input():
28+
n,p = line.strip().split()
29+
n = int(n)
30+
p = int(p)
31+
32+
print(binomial_coefficients[n][p])
33+

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
150150
* [Tower Of Hanoi](/Math/TowerofHanoi)
151151
* [Truncated Square Root](/Math/truncated_square_root)
152152
* [Calculate And Print All Permutations](/Math/AllPermutations)
153+
* [Calculate the result of binom(n,p)](/Math/binomial_coefficients)
153154
* [Network Flow](/NetworkFlow)
154155
* [Dinic](/NetworkFlow/Dinic)
155156
* [Edmund Karp](/NetworkFlow/EdmundKarp)
@@ -162,7 +163,7 @@ ACM-ICPC Algorithms is a collection of important algorithms and data structures
162163
* [Jump Search](/Search/JumpSearch)
163164
* [Linear Search](/Search/LinearSearch)
164165
* [Ternary Search](/Search/TernarySearch)
165-
* [Interpolation Search](/Search/InterpolationSearch)
166+
* [Interpolation Search](/Search/InterpolationSearch)
166167
* [Sorting Algorithms](/Sorting)
167168
* [Bubble Sort](/Sorting/bubble%20sort)
168169
* [Cocktail Shaker Sort](/Sorting/CocktailShakerSort)

0 commit comments

Comments
 (0)