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) = 5
r (int) = 2
Returns (int) 10

Example 2

Input
n (int) = 6
r (int) = 0
Returns (int) 1

Example 3

Input
n (int) = 3
r (int) = 5
Returns (int) 0

Use 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 result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.