![]() |
VOOZH | about |
Given three values, N, L and R, the task is to calculate the sum of binomial coefficients (nCr) for all values of r from L to R.
Examples:
Input: N = 5, L = 0, R = 3
Output: 26
Explanation: Sum of 5C0 + 5C1 + 5C2 + 5C3 = 1 + 5 + 10 + 10 = 26.Input: N = 3, L = 3, R = 3
Output: 1
Approach(Using factorial function): Solve this problem by straightforward calculating nCr by using the formula n! / (r!(nār)!) and calculating factorial recursively for every value of r from L to R.
Below is the implementation of the above approach:
26
Time Complexity: O(N * (R - L))
Auxiliary Space: O(N)
Approach (Without using factorial function): This approach for finding the sum of binomial coefficients (nCr) for all values of r from L to R can be implemented using two nested loops. The outer loop will iterate from L to R, and the inner loop will calculate the binomial coefficient for each value of r using the formula:
nCr = n! / (r! * (n-r)!)
where n is the given number, r is the current value of the inner loop, and ! denotes the factorial function.
The sum of all binomial coefficients can be accumulated in a variable initialized to zero before the loops start.
Steps to implement the above approach:
26
Time Complexity: O(N * (R - L))
Auxiliary Space: O(N)