Python Implementation of Problem 2

View source code here on GitHub!

Includes

Problem Solution

Project Euler Problem 2

I also decided that I like lazy functions on this one. Also seen: generator comprehensions

Revision 1:

I split fib() up so that there is one version which limits and another which does not.

Revision 2:

Utilize the underlying pattern of the sequence to avoid needing modulo divison, speeding up by ~2x.

Problem:

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.

python.src.p0002.main() int
 1"""
 2Project Euler Problem 2
 3
 4I also decided that I like lazy functions on this one. Also seen: generator
 5comprehensions
 6
 7Revision 1:
 8
 9I split fib() up so that there is one version which limits and another which
10does not.
11
12Revision 2:
13
14Utilize the underlying pattern of the sequence to avoid needing modulo divison,
15speeding up by ~2x.
16
17Problem:
18
19Each new term in the Fibonacci sequence is generated by adding the previous two
20terms. By starting with 1 and 2, the first 10 terms will be:
21
221, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
23
24By considering the terms in the Fibonacci sequence whose values do not exceed
25four million, find the sum of the even-valued terms.
26
27"""
28from .lib.fibonacci import fib_by_3
29
30
31def main() -> int:
32    f = fib_by_3()  # this works because every third value is even
33    answer = val = 0
34    while val < 4_000_000:
35        answer += val
36        val = next(f)
37    return answer

Tags: fibonacci-number, divisibility