This is my solution to Project Euler problem 2:
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
The class fibonacci_Even_Sum_Calculator
does two things:
- calculate the sum of the even-valued Fibonacci numbers
- cache the results in a dictionary
Is this a sign that this code violates the Single Responsibility Principle?
class fibonacci_Even_Sum_Calculator:
def __init__(self):
self.cached_result = dict()
def F(self, n):
if n == 0:
return 0
elif n == 1:
return 1
else:
if(self.cached_result.has_key(n)):
return self.cached_result[n]
else:
result = self.F(n-1) + self.F(n-2)
self.cached_result[n] = result
return result
def is_even(self, number):
return number % 2 == 0
def get_result(self,limit_value):
sequence = 2
sum = 0
while True:
result = self.F(sequence)
if result > limit_value:
break
if self.is_even(result) :
sum = sum + result
sequence = sequence + 1
return sum
fibonacci_calculator = fibonacci_Even_Sum_Calculator()
result = fibonacci_calculator.get_result(4000000)
print result