VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-of-binomial-coefficients-ncr-in-a-given-range/

⇱ Sum of binomial coefficients (nCr) in a given range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of binomial coefficients (nCr) in a given range

Last Updated : 7 Nov, 2023

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:



Output
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:

  • Declare and initialize the variables N, L, and R  respectively.
  • Call the sumOfnCr function, passing N, R, and L as arguments.
  • Within the sumOfnCr function, declare a long long variable named res and initialize it to 0.
  • Start a for loop with a variable r, which runs from L to R.
  • Within the for loop, declare a long long variable named nCr and initialize it to 1.
  • Start another for loop with a variable i, which runs from 1 to r.
  • Within the inner for loop, multiply nCr by (n-i+1) and then divide it by i.
  • After the inner for loop ends, add nCr to the res variable.
  • After the outer for loop ends, return the res variable.
  • End the sumOfnCr function.
  • Print the result of the sumOfnCr function using cout.

Output
26

Time Complexity: O(N * (R - L))
Auxiliary Space: O(N)
 

Comment