Find sum of even index binomial coefficients in C++


Consider we have a number n, we have to find the sum of even indexed binomial coefficients like $$\left(\begin{array}{c}n\ 0\end{array}\right)+\left(\begin{array}{c}n\ 2\end{array}\right)+\left(\begin{array}{c}n\ 4\end{array}\right)+\left(\begin{array}{c}n\ 6\end{array}\right)+...\left(\begin{array}{c}4\ 0\end{array}\right)+\left(\begin{array}{c}4\ 2\end{array}\right)+\left(\begin{array}{c}4\ 4\end{array}\right)++=1+6+1=8$$

So here we will find all the binomial coefficients, then only find the sum of even indexed values.

Example

 Live Demo

#include<iostream>
using namespace std;
int evenIndexedTermSum(int n) {
   int coeff[n + 1][n + 1];
   for (int i = 0; i <= n; i++) {
      for (int j = 0; j <= min(i, n); j++) {
         if (j == 0 || j == i)
            coeff[i][j] = 1;
         else
            coeff[i][j] = coeff[i - 1][j - 1] + coeff[i - 1][j];
      }
   }
   int sum = 0;
   for (int i = 0; i <= n; i += 2)
   sum += coeff[n][i];
   return sum;
}
int main() {
   int n = 8;
   cout << "Sum of even placed binomial coefficients: " <<evenIndexedTermSum(n);
}

Output

Sum of even placed binomial coefficients: 128

Updated on: 18-Dec-2019

86 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements