Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbbad761

Browse files
Luke-Polsonkeon
authored andcommitted
Add recursive binomial coefficient (keon#598)
* added recursive binomial coefficient algorithm* updated readme link* changed return to raise exceptioninstead of returning a string when inputs are invalid, function now raises a ValueError exception
1 parentb456670 commitbbad761

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,7 +217,8 @@ If you want to uninstall algorithms, it is as simple as:
217217
-[sqrt_precision_factor](algorithms/maths/sqrt_precision_factor.py)
218218
-[summing_digits](algorithms/maths/summing_digits.py)
219219
-[hailstone](algorithms/maths/hailstone.py)
220-
- [find_order](algorithms/maths/find_order_simple.py)
220+
-[recursive_binomial_coefficient](algorithms/maths/recursive_binomial_coefficient.py)
221+
-[find_order](algorithms/maths/find_order_simple.py)
221222
- [find_primitive_root](algorithms/maths/find_primitive_root_simple.py)
222223
-[matrix](algorithms/matrix)
223224
-[sudoku_validator](algorithms/matrix/sudoku_validator.py)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
defrecursive_binomial_coefficient(n,k):
2+
"""Calculates the binomial coefficient, C(n,k), with n>=k using recursion
3+
Time complexity is O(k), so can calculate fairly quickly for large values of k.
4+
5+
>>> recursive_binomial_coefficient(5,0)
6+
1
7+
8+
>>> recursive_binomial_coefficient(8,2)
9+
28
10+
11+
>>> recursive_binomial_coefficient(500,300)
12+
5054949849935535817667719165973249533761635252733275327088189563256013971725761702359997954491403585396607971745777019273390505201262259748208640
13+
14+
"""
15+
16+
ifk>n:
17+
raiseValueError('Invalid Inputs, ensure that n >= k')
18+
#function is only defined for n>=k
19+
ifk==0orn==k:
20+
#C(n,0) = C(n,n) = 1, so this is our base case.
21+
return1
22+
ifk>n/2:
23+
#C(n,k) = C(n,n-k), so if n/2 is sufficiently small, we can reduce the problem size.
24+
returnrecursive_binomial_coefficient(n,n-k)
25+
else:
26+
#else, we know C(n,k) = (n/k)C(n-1,k-1), so we can use this to reduce our problem size.
27+
returnint((n/k)*recursive_binomial_coefficient(n-1,k-1))
28+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp