用 Python 编写程序来求前 n 个奇数之和
pythonserver side programmingprogramming更新于 2026/1/12 1:16:17
假设我们有一个数字 n,我们必须求出前 n 个正奇数之和。
因此,如果输入是 7,则输出将是 49,因为 [1+3+5+7+9+11+13] = 49
要解决这个问题,我们将遵循以下步骤 −
- 如果 n 与 0 相同,则
- 返回 0
- sum := 1, count := 0, temp := 1
- 当 count < n-1 时,执行
- temp := temp + 2
- sum := sum + temp
- count := count + 1
- 返回 sum
让我们看看下面的实现以便更好地理解 −
示例
class Solution: def solve(self, n): if n == 0: return 0 sum = 1 count = 0 temp = 1 while(count<n-1): temp += 2 sum += temp count += 1 return sum ob = Solution() print(ob.solve(7))
输入
7
输出
49
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

