Intermediate Level
Implement the nCrValue method that calculates the binomial coefficient value nCr.
The input contains two integers n and r. Your task is to return the value of nCr, which means the number of ways to choose r items from n items.
For example, 5C2 is 10 because there are ten different ways to choose two items from five. If r is greater than n, return 0.
Example 1
Input
n (int) =
5r (int) =
2Returns (int)
10Example 2
Input
n (int) =
6r (int) =
0Returns (int)
1Example 3
Input
n (int) =
3r (int) =
5Returns (int)
0Use the combination formula, but calculate it step by step instead of directly computing large factorials.
Because nCr is the same as nC(n-r), use the smaller value between r and n-r. Then multiply and divide in each step to build the final result.
Pseudocode:
function nCrValue(n, r):
if r > n:
return 0
r = minimum(r, n - r)
result = 1
for i from 1 to r:
result = result * (n - r + i)
result = result / i
return resultReady to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run