Project Euler Problem 002
http://projecteuler.net/index.php?section=problems&id=2
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
フィボナッチ数の偶数だけ加算していけばいいのだけど、
「奇数 奇数 偶数 奇数 奇数 偶数」のパターンで偶数が出てくるので偶数の数だけ取り出す。
もっとズバッとした回答がありそうやけど、全然分かりませんな。
#!/usr/bin/env python class even_fib: def __init__(self, limit=100): self.a = 1 self.b = 1 self.limit = limit def __iter__(self): return self def next(self): val = self.a + self.b if val < self.limit: self.a = val + self.b self.b = val + self.a return val else: raise StopIteration print sum([x for x in even_fib(4000000)])
答え: 4613732