41 lines
993 B
Python
41 lines
993 B
Python
#!/usr/bin/python3
|
|
|
|
# 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.
|
|
|
|
from timeit import default_timer
|
|
|
|
def main():
|
|
|
|
start = default_timer()
|
|
|
|
N = 4000000
|
|
|
|
fib1 = 1
|
|
fib2 = 2
|
|
fibn = fib1 + fib2
|
|
sum_ = 2
|
|
|
|
# Simple brute-force approach: generate every value in the Fibonacci
|
|
# sequence smaller than 4 million and if it's even add it to the total.
|
|
while fibn < N:
|
|
if fibn % 2 == 0:
|
|
sum_ = sum_ + fibn
|
|
|
|
fib1 = fib2
|
|
fib2 = fibn
|
|
fibn = fib1 + fib2
|
|
|
|
end = default_timer()
|
|
|
|
print('Project Euler, Problem 2')
|
|
print('Answer: {}'.format(sum_))
|
|
|
|
print('Elapsed time: {:.9f} seconds'.format(end - start))
|
|
|
|
if __name__ == '__main__':
|
|
main()
|