Project Euler - 2

피보나치 수

4백만 미만의 피보나치 수 중에서 짝수인 것들의 합을 구하라.
"""
Even Fibonacci numbers

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.
"""


class Fibonacci:
def __init__(self):
self.a = 0
self.b = 1

def __iter__(self):
return self

def __next__(self):
c = self.a + self.b
if self.a > self.b:
self.b = c
else:
self.a = c
return c


if __name__ == '__main__':
s = 0
fibonacci = Fibonacci()
for n in fibonacci:
if n >= 4000000:
break
else:
if n % 2 == 0:
s += n
print(s)
피보나치 수열을 구하기 위해서 Iterator 클래스를 구현하였다.

댓글

이 블로그의 인기 게시물

Project Euler - 3

메인 스크립트

예외 처리