Project Euler Problem 002
Statement
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, …
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
Solution
Not much explanation. As we generate the fibonacci sequence we check if the generated number is even and add it.
Once you reach 4000000, exit and print the result
if __name__ == '__main__': result = 0 i1, i2 = (1, 2) while i2 < 4000000: result += ((i2 & 1) == 0) and i2 or 0 i1, i2 = (i2, i1 + i2) print("The result is:", result)
Python file is available for download here.