Here is the description for the second problem from Project Euler:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
The Fibonacci sequence starts with the numbers 1 and 1 (or 0,1 or 1,2) and each new term is generated by adding the previous two. For example, the first ten terms of the Fibonacci sequence are 1, 1, 2, 3, 5, 8, 13, 21, 34, and 55.
At first glance, I thought the sum would grow unreasonably large, but I learned something surprising: there are only 33 Fibonacci numbers less than four million and only eleven of them are even.
Here’s my solution in Python:
a = 1 b = 1 c = a+b sum = 0 while c <= 4000000: if c%2==0: sum = sum + c a = b b = c c = a+b print sum
The result is 4,613,732.
Notes
After completing this problem, I remembered that Python offers some cute syntax to make this easier. In my program above, note that I use a third variable c to help find the next Fibonacci number, a fairly typical pattern in most programming languages. Python lets you do the following:
a,b = 1,1 sum = 0 while b <= 4000000: if b%2==0: sum = sum + b a,b = b,a+b print sum
Pingback: Modeling the Zombie Apocalypse | Math 老师