-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path002-even_fibonacci_numbers.js
76 lines (58 loc) · 1.11 KB
/
002-even_fibonacci_numbers.js
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
/* Alternate Solution */
let fiboEvenSum2 = (limit) => {
let sum = 0
let a = 1
let b = 2
console.log(a)
console.log(b)
if(limit >= 2){
sum = sum + b
}
let c = 3
while(c <= limit){
console.log(c)
if(c % 2 === 0){
sum = sum + c
}
a = b
b = c
c = a + b
}
return sum
}
let fibNumbers = []
/* Generates Fibonacci Numbers Under a Given Limit */
let generateFibNumbers = (limit) => {
// Base Case
let a = 0;
let b = 1;
fibNumbers.push(a)
fibNumbers.push(b)
// Generate Remaing Fib Numbers
let i;
for(i = 2; i < limit; i ++){
let c = a + b
// Stopping Condition -> when we reach our limit
if(c > limit){
return;
}
fibNumbers.push(c)
a = b
b = c
}
}
/* Solution Function */
let fiboEvenSum = (limit) => {
generateFibNumbers(limit)
// Remove Odd Numbers
let evenFibNumbers = fibNumbers.filter((number) => {
return number % 2 === 0
})
// Sum Even Fib Numbers
let sum = 0;
evenFibNumbers.forEach((number) => {
sum = sum + number
})
return sum
}
console.log(fiboEvenSum(1000))