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
Return:
(int) 10
Example 2
Input:
n (int) = 6
r (int) = 0
Return:
(int) 1
Example 3
Input:
n (int) = 3
r (int) = 5
Return:
(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
Run your code to see the result.