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:
- How could I pick out the evens?
- How could I add those evens without actually assigning them to a variable?
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!
Even numbers are the ones that leave a remainder of zero when you divide them by 2 (in integers). In Python, we get ‘the remainder after dividing as an integer’ with the
%operator.However, there’s another neat trick you can do here. The even Fibonacci numbers are every third number in the sequence, and if you can rigorously prove why, then you’ll be close to getting the formula needed to just generate the sequence of even Fibonacci numbers directly.
What’s wrong with assigning them to a variable? Just set up another one for the running count.