Skip to content

Instantly share code, notes, and snippets.

@amoshyc
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save amoshyc/a356bc530ed7b4a02031 to your computer and use it in GitHub Desktop.

Select an option

Save amoshyc/a356bc530ed7b4a02031 to your computer and use it in GitHub Desktop.
Project Euler #2
def fib():
    f0 = 1
    f1 = 2

    yield f0
    yield f1

    f = f0 + f1
    while f <= 4000000:
        yield f
        f0 = f1
        f1 = f
        f = f0 + f1

print(sum([x for x in fib() if x % 2 == 0]))

output = 4613732

##另解 This may be a small improvement. The Fibonacci series is:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610...

Now, replacing an odd number with O and an even with E, we get:

O, O, E, O, O, E, O, O, E, O, O, E, O, O, E...

And so each third number is even. We don't need to calculate the odd numbers.
Starting from an two odd terms x, y, the series is:

x, y, x + y, x + 2y, 2x + 3y, 3x + 5y...

the even terms are x+y and 3x+5y...

so the code is

total = 0
x = 1
y = 1
while x + y <= 4000000:
    total += (x + y)
    x, y = x + 2 * y, 2 * x + 3 * y

print(total)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment