You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Python程序计算等比数列1+2+4+…+n的和,参考指定代码格式

Solution to Calculate the Sum of the Geometric Series 1 + 2 + 4 + ... + n

Got it, let's work through this problem. We need to compute the sum of a geometric series where each term doubles the previous one, starting at 1 and ending at the input value n.

First, a quick pattern check: each term here is a power of 2 (1=2⁰, 2=2¹, 4=2², etc.). The sum of this series up to 2ᵏ is actually 2ᵏ⁺¹ - 1—this is why when the input is 256 (which is 2⁸), the sum is 511 (2⁹ - 1). But let's build the solution following the iterative structure of the sample code you provided.

The Code

n = int(input("Enter n: "))
total = 0
current_term = 1
# Loop through each term until we exceed the input n
while current_term <= n:
    total += current_term
    current_term *= 2  # Double the term to get the next in the sequence
print()
print("The sum is: %s" % (total))

How It Works

  • We start by grabbing the input n and initializing total (our sum accumulator) to 0.
  • current_term starts at 1, the first term of the series.
  • In each loop iteration, we add the current term to our total, then double the term to get the next value in the sequence.
  • We stop looping once current_term grows larger than n, so we never add terms that exceed the input value.

Example Verification

If you input 256, the loop processes terms 1, 2, 4, 8, 16, 32, 64, 128, 256. Adding these up gives 511, which matches the expected result.

Even if you input a value that's not a perfect power of 2 (like 10), the code works correctly: it sums 1+2+4+8 = 15, since 16 is larger than 10 and gets excluded from the sum.

内容的提问来源于stack exchange,提问作者 Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:32:29