Eulerproject 2 Fibonacci calculation
Eulerproject 2 Fibonacci calculation
I am as new as you can be to Python and trying to learn by following a few guides and doing little projects simultaneously.
I am currently trying to do the 2nd Eulerproject question regarding Fibonacci numbers. It goes as follows:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
And this was my attempt at solving it
Fib = [1, 2, 3]
answer_list =
x = Fib[-1]
y = Fib[-2]
while x <= 4000000:
z = x + y
Fib.append(z)
for number in Fib:
if number % 2 == 0:
answer_list.append(number)
answer = sum(answer_list)
print(answer)
When I try to use this code I do not get a response. Can anyone, if possible without giving me the actual answer, point me in the right direction on how to improve?
Thanks in advance and kind regards.
x
x = Fib[-1]
while
@DavidG actually you solved my problem, thank you. I had to keep the line inside as well as outside the while loop because otherwise nothing is defining 'x' for the 'while' line itself, surely there is a more elegant way of phrasing this..🤔
– davidmilad
Jul 2 at 13:47
1 Answer
1
Much simpler and faster way to do the same:
fib = [1, 1] # something to start with
while fib[-1] < 4000000 :
fib.append( fib[-1] + fib[-2] )
print sum( i for i in fib if i&1 == 0 )
outputs:
4613732
If the upper limit is much higher than 4e6, a better approach would be to avoid creating large lists and just use two variables previous
and current
for the Fibonacchi numbers generation, and one extra variable to keep the sum of the even elements. Something along the lines of:
previous
current
>>> total = 0
>>> current = previous = 1
>>> while current < 4000000 :
... if current & 1 == 0 : total += current
... previous, current = current, previous + current
...
>>> total
4613732
One extra word of the warning, the last number over 4e6 is 5702887 -- an odd number, so I did not care about removing it from the list in the first code sample. But if you want to be extra careful, add fib.pop()
before summing the elements.
fib.pop()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You don't ever change
x
, therefore you are stuck in the while loop. You probably want to dox = Fib[-1]
inside thewhile
– DavidG
Jul 2 at 13:41