C++ 实现级数 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+....+(2n-1)) 的求和
在这个问题中,我们给定一个整数 n。我们的任务是创建一个程序来求级数 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+....+(2n-1)) 的和。
从这个级数中,我们可以观察到级数的第 i 项是前 i 个奇数的和。
让我们举个例子来理解这个问题:
输入
n = 3
输出
14
解释 −(1) + (1+3) + (1+3+5) = 14
解决这个问题的一个简单方法是使用嵌套循环,然后将所有奇数加到一个 sum 变量中。然后返回 sum。
示例
程序说明了解决方案的工作原理:
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
int sum = 0, element = 1;
for (int i = 1; i <= n; i++) {
element = 1;
for (int j = 1; j <= i; j++) {
sum += element;
element += 2;
}
}
return sum;
}
int main() {
int n = 12;
cout<<"Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2"<<n<<"-1)) is "<<calcSeriesSum(n);
return 0;
}输出
Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*12-1)) is 650
这种方法效率不高,因为它使用了两个嵌套循环。
一种更高效的方法是从数学上找到求级数和的通用公式。
n 个奇数的和:
= (1) + (1+3) + (1+3+5) + … (1+3+5+... + 2n-1)
= n²
首先,让我们看看前 n 个奇数的和,它代表级数的各个元素。
级数的和:
sum = (1) + (1+3) + (1+3+5) + … + (1+3+5+ … + 2n-1) sum = ∑ (1+3+5+ … + 2n-1) sum = ∑ n2 sum = [n * (n+1) * (2*n -1)]/6
示例
程序说明了解决方案的工作原理:
#include <iostream>
using namespace std;
int calcSeriesSum(int n) {
return ( n*(n + 1)*(2*n + 1) )/6;
}
int main() {
int n = 9;
cout<<"Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*"<<n<<"-1)) is "<<calcSeriesSum(n);
return 0;
}输出
Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ... + (1+3+5+7+ ... + (2*9-1)) is 285
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP