project euler question 2 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

project euler question 2

i've started working on the Project Euler codeing problems to get more familiar with coding. For question 2 my code seems to "exceed the memory limit". I can't tell if I did something wrong or if my computer just can't handle that many numbers. I would appreciate it if someone could tell me if my code is correct or not. Thank you it reads as: a = sum([x for x in range (4000000) if ((x%2 ==0))]) print(str(a))

5th Apr 2018, 7:34 PM
James Hunter
James Hunter - avatar
4 Answers
+ 2
Your code worked on my PC, but I think the problem is that you're creating a list. Try to use a generator, instead. a = sum(x for x in range(4000000) if (x % 2 == 0)) print(a) Note that I just removed the brackets.
5th Apr 2018, 7:46 PM
Maicon Mauricio
Maicon Mauricio - avatar
+ 1
See what Gauss did http://mathcentral.uregina.ca/QQ/database/QQ.02.06/jo1.html its not the final answer but it will point you in the right direction
5th Apr 2018, 7:43 PM
Louis
Louis - avatar
+ 1
Thanks everyone! I really appreciate your help
5th Apr 2018, 10:16 PM
James Hunter
James Hunter - avatar
0
gives output: 3999998000000 probably is that your computer can't handle it. if i read that correctly it adds every even number between 0 and 3999999 together 2+4+6+8+10+12+14+16 and so on.
5th Apr 2018, 7:39 PM
Markus Kaleton
Markus Kaleton - avatar