I was solving a Project Euler problem that goes as follows:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
So I used this script to print the Fibonacci sequence up to four million:
a = 0
b = 1
while b < 4000000:
print b
a, b = b, a+b
Obviously, I could run this and just manually add the even values, but I would feel like I'm cheating.
Technically, I guess I'm asking two questions:
Oh, and I'm sure its extremely evident, but I'm very new to...well, programming in general and I can get lost in experts' verbosity easily. Thanks in advance!
If you're averse to variable assignments, you might enjoy a functional approach:
>>> from itertools import takewhile, ifilter
>>> def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
>>> def is_even(x):
return x % 2 == 0
>>> sum(ifilter(is_even, (takewhile(lambda x: x<4000000, fib()))))
4613732
Ah, Project Euler!
This is more a math question than a programming question, though.
On the programming side, simply add an accumulator. You can test for evenness by using the modulo operator %
, which returns the integer remainder after dividing the left operand by the right operand.
a, b = 0, 1
evens = 0
while b < 4000000:
if not b%2:
evens += b
a, b = b, a+b
Once you have the answer, the Project Euler PDF and forums will fill you in on the mathy part of this problem and really answer your questions. There are ways to avoid having to calculate every Fibonacci number and having to test for evenness, but these require exploiting specific mathematical properties of the Fibonacci sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With