用 C++ 求二项式系数偶数索引的和


考虑我们有一个数字 n,我们需要找到偶数索引二项式系数的和,比如 $$\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$$

所以这里我们会找出所有二项式系数,然后再找出偶数索引值的和。

示例

 在线演示

#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);
}

输出

Sum of even placed binomial coefficients: 128

更新于: 18-Dec-2019

112 次浏览

开启您的 职业 生涯

完成课程并获得认证

开始
广告