等差数列通项怎么编程

时间:2025-03-04 23:58:07 明星趣事

等差数列的通项公式是 `an = a1 + (n-1)d`,其中 `a1` 是首项,`d` 是公差,`n` 是项数。

下面是一个使用 Python 编写的等差数列通项公式函数:

```python

def arithmetic_sequence_term(a1, d, n):

"""

计算等差数列的第 n 项

参数:

a1 (int): 首项

d (int): 公差

n (int): 项数

返回:

int: 等差数列的第 n 项

"""

return a1 + (n - 1) * d

示例使用

a1 = 1 首项

d = 2 公差

n = 5 项数

an = arithmetic_sequence_term(a1, d, n)

print(f"The {n}th term of the arithmetic sequence is: {an}")

```

这个函数接受三个参数:首项 `a1`、公差 `d` 和项数 `n`,然后返回等差数列的第 `n` 项。你可以根据需要修改 `a1`、`d` 和 `n` 的值来计算不同等差数列的通项。