简体   繁体   中英

I'm brand new and working on Project Euler #2 in python

The goal is to sum up every even number up to 4 million. I thought this would work but the program gets stuck running. Think it has to do with the if statement, but lost otherwise. Here's what I have.

list = []
a, b = 0, 1
while b <40:
    if b%2 == 0:
        list.append(b)
        a, b = b, a+b

t=sum(list)
print(t)

This here is your biggest problem:

a, b = b, a+b

It has so much potential to mess up your loop! And like others mentioned it doesn't even update anything when b is odd, only when it is even, and then you're stuck.

Why not do this the simple way, with range:

mysum = sum([i for i in range(0, 40, 2)])

Will take care of everything with one line (and of course, replace 40 with 4,000,001 for your question, if you want to include the number 4,000,000 as well. If you just want everything up to it but not to include it, use just 4,000,000)

        a, b = b, a+b

This line only runs if b % 2 == 0. I think you meant to run it every time. It should be indented one layer further out.

One can also use the mathematics rule where the sum of integers between 1 and n is equal to n*(n+1)/2 . If we want to sum only even numbers, it is like considering only half the number to sum and multiply the result with two.

fSumEvenNumbers = lambda x: (x//2)*(x//2+1)

This would give

fSumEvenNumbers(40000000)

which is equivalent to

(2e7)**2 + 2e7
4e14 + 2e7
400000020000000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM