-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem2.py
79 lines (55 loc) · 1.74 KB
/
Problem2.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Code by @AmirMotefaker
# projecteuler.net
# https://projecteuler.net/problem=2
# Even Fibonacci numbers
# 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.
# Solution 1
import time
start_time = time.time() #Time at the start of program execution
def IsEven(n):
if n % 2 == 0:
return True
else:
return False
first = 1
second = 2
sum = 0
while (first < 4000000):
# print ("my first number is", first)
if IsEven(first):
# print ("oh it is even")
sum = sum + first
# print ("-----------> now the sum is", sum)
new = first + second
first = second
second = new
print(sum)
end_time = time.time() #Time at the end of execution
print ("Time of program execution:", (end_time - start_time)) # Time of program execution
# Solution 2
import time
start_time = time.time() #Time at the start of program execution
a, b = 1, 1
total = 0
while a <= 4000000:
if a % 2 == 0:
total += a
a, b = b, a+b # the real formula for Fibonacci sequence
print (total)
end_time = time.time() #Time at the end of execution
print ("Time of program execution:", (end_time - start_time)) # Time of program execution
# def sum_even_fibonacci(limit)
# '''Return the sum of all even Fibonacci numbers
# not greater than LIMIT
# '''
# a, b = 1, 1
# total = 0
# while a <= limit:
# if a % 2 == 0:
# total += a
# a, b = b, a+b
# return total
### Answer: 4613732