-
Notifications
You must be signed in to change notification settings - Fork 0
/
evenfibonacci.py
executable file
·57 lines (37 loc) · 1.32 KB
/
evenfibonacci.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python3
"""
projetceuler.net
Problem 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, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
fibonacci function based on Binet's Fibonacci Number Formula
(1 + sqrt(5))n - (1 - sqrt(5))n
Fn = -------------------------------
2n sqrt(5)
"""
import math
import datetime
sqrt = math.sqrt
t = 0
n = 0
while int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))) < 4000000:
if int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))) % 2 == 0:
# print( "Even",n,int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))))
t = t + int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
n = n + 1
print( "Binet's Fibonacci Number Formula: ",t)
# Solution using phi thecodeaddict.wordpress.com/tag/golden-ratio
from math import sqrt
limit, current, sum = 4000000, 2, 0
phi3 = ((1+sqrt(5))/2)**3
while sum < limit:
sum += current
current = round(phi3*current)
print ("Answer using Phi golden ratio",sum)
evenSum, a, b = 0, 1, 2
while a < 4000000:
if b % 2 == 0:
evenSum += b
a, b = b, a+b
print("Answer using Even Sum = ", evenSum)