-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2-add-Even-Fibonacci-Num.js
More file actions
executable file
·62 lines (44 loc) · 1.85 KB
/
2-add-Even-Fibonacci-Num.js
File metadata and controls
executable file
·62 lines (44 loc) · 1.85 KB
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
/* 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.
n-th Fib Num = 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ...
Actual Fib Num = 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 ...
The final solution to this is - The result of all even numbered Fibonacci numbers less than 4M: 4613732
https://www.mathblog.dk/project-euler-problem-2/
BUT my ans in SOL-2 is different, as I am initiation i, j with 0 and 1.
*/
// SOL-1
addEvenFibNum_1 = num => {
var i = 1,
j = 2,
sum = 2;
while (j < 4000000) {
var k = j;
j += i; // Updating j to take up the next Fibonacci Sequence Number by adding its previous number with its current value
i = k; // Updating i to take up the next consecutive number (which is the previous value of j)
if ((j % 2) === 0) {
sum += j;
}
}
return sum;
}
console.log('Total Sum of even numbered Fibonacci sequence less that 4 million is :' + addEvenFibNum_1(4000000));
// SOL-2 - I gnerally follow this initialization value always
addEvenFibNum_2 = num => {
var i = 0,
j = 1,
fib = 1;
evenSum = 1;
while (j < 4000000) {
fib = i + j;
j = fib; // Updating j to take up the next Fibonacci Sequence Number by adding its previous number with its current value
i = fib - i; // Updating i to take up the next consecutive number (which is the previous value of j)
if ((j % 2) === 0) {
evenSum += j;
}
}
return evenSum;
}
console.log('Total Sum of even numbered Fibonacci sequence less that 4 million is :' + addEvenFibNum_2(4000000));