Project Euler第2题代码结果异常求助:为何求和结果不符?
Let's break down why your original code gives an incorrect result, and why changing the condition accidentally gives the right answer (spoiler: it's a coincidence!).
First, Let's Walk Through Your Original Code
Your code initializes a = b = 1, then builds a list i by appending a in each loop before updating a and b. Here's what happens step-by-step for the early terms:
- Start:
a=1, b=1→ append1toi, thena=1, b=2 - Next loop:
b=2 ≤ 4000000→ append1toi, thena=2, b=3 - Next loop:
b=3 ≤4000000→ append2toi, thena=3, b=5 - ... and so on.
The critical problem comes at the end of the sequence:
When a=2178309 and b=3524578 (which is ≤4000000), your code appends 2178309 to i, then updates a=3524578 and b=5702887 (which is >4000000). The loop stops here, so the value 3524578 (a valid even Fibonacci number ≤4000000) never gets added to your list i.
That's why your original sum of even terms is 1089154—it's missing the largest even term 3524578. Adding that term gives the correct total: 1089154 + 3524578 = 4613732.
Why Changing the Condition Gave the Correct Answer (By Coincidence!)
When you changed the filter to x % 2 (keep odd terms), you calculated the sum of all odd terms in your incomplete list i. Let's do the math:
- The sum of all Fibonacci terms ≤4000000 is
9227464(this follows from the Fibonacci property: sum of first n terms = F(n+2)-1). - The sum of your incomplete list
i(all terms up to2178309) is5702886. - Sum of odd terms in
i=5702886 - 1089154 = 4613732—which just happens to equal the sum of all even terms in the complete sequence. This is a coincidence, not a fix for your logic.
How to Fix Your Original Code
To capture all valid Fibonacci terms ≤4000000, adjust your loop condition to check a instead of b, so you append each term before it's updated:
a = b = 1 i = [] while a <= 4000000: # Check if current a is within the limit i.append(a) a, b = b, a + b e = [x for x in i if not x % 2] print(sum(e))
This will include 3524578 in your list i, and the sum will correctly output 4613732.
Alternatively, you can optimize the code to avoid building a list entirely (more efficient for large limits):
total = 0 a, b = 1, 2 while b <= 4000000: if b % 2 == 0: total += b a, b = b, a + b print(total)
内容的提问来源于stack exchange,提问作者weakit

