Python计算等差数列前n项和
时间: 2024-10-25 08:09:33 浏览: 54
python 等差数列末项计算方式
5星 · 资源好评率100%
在Python中,计算等差数列的前n项和(通常称为求和Sn)可以用数学公式直接计算,也可以使用循环结构实现。以下是两种常见的方式:
**使用数学公式**(适用于已知首项a1和公差d的情况):
```python
def arithmetic_series_sum(n, a1, d):
return n * (a1 + a1 + (n - 1) * d) / 2
# 示例
n_terms = 5
first_term = 1
common_difference = 2
total_sum = arithmetic_series_sum(n_terms, first_term, common_difference)
print("等差数列前{}项和为:{}".format(n_terms, total_sum))
```
**使用循环**(通用方法,适用于任何情况):
```python
def sum_of_arithmetic_sequence(n, sequence):
total = 0
for i in range(1, n+1):
total += sequence[i-1] # 注意索引从0开始,所以是sequence[i-1]
return total
# 示例,需要先初始化等差数列
first_term = 1
common_difference = 2
sequence = [first_term + i * common_difference for i in range(n_terms)]
total_sum = sum_of_arithmetic_sequence(n_terms, sequence)
print("等差数列前{}项和为:{}".format(n_terms, total_sum))
```
阅读全文