系列1 ^ 2 + 3 ^ 2 + 5 ^ 2 +的总和。。。+(2 * n-1)^ 2在C ++中
在这个问题上,我们得到级数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