C++ 中 1^2 + 3^2 + 5^2 + . . . + (2*n - 1)^2 級數的和


在這個問題中,我們給定了一個級數的數字 n。我們的任務是找到給定 n 值時級數 1^2 + 3^2 + 5^2 +... + (2*n - 1)^2 的和。

讓我們舉一個例子來理解這個問題,

輸入

n = 5

輸出

84

解釋

sum = 1^2 + 3^2 + 5^2 + 7^2 + 9^2
= 1 + 9 + 25 + 49 = 84

解決此問題的一種基本方法是直接應用級數求和公式。

示例

 現場演示

#include <iostream>
using namespace std;
int calcSumOfSeries(int n) {
   int sum = 0;
   for (int i = 1; i <= n; i++)
   sum += (2*i-1) * (2*i-1);
   return sum;
}
int main() {
   int n = 5;
   cout<<"The sum of series up to "<<n<<" is "<<calcSumOfSeries(n);
   return 0;
}

輸出

The sum of series up to 10 is 165

另一種解決方法是使用數學公式來找到級數的和。

總和為,

1^2 + 3^2 + 5^2 + … + (2*n - 1)^2 =
{(n * (2*(n-1)) * (2*(n+1)))/3}

示例

 現場演示

#include <iostream>
using namespace std;
int calcSumOfSeries(int n) {
   return (n * (2 * n - 1) * (2 * n + 1)) / 3;
}
int main() {
   int n = 5;
   cout<<"The sum of series up to "<<n<<" is "<<calcSumOfSeries(n);
   return 0;
}

輸出

The sum of series up to 5 is 165

更新於: 2020-08-05

401 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.