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.
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