-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalgorithm12.html
44 lines (28 loc) · 1.11 KB
/
algorithm12.html
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
<!DOCTYPE html>
<html>
<body>
<script>
//https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers
//Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num.
// The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8.
// For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.
function sumFibs(num) {
var arr = [1,1];
for (var i=2 ;(arr[i-1] + arr[i-2]) <= num;i++ ) {
arr[i] = (arr[i-1] + arr[i-2]);
if(arr[i]==num) {
break;
}
}
return arr.filter(number => (number%2 !== 0)).reduce((a,b) => (a+b));
}
//tests
console.log(sumFibs(4));
console.log(sumFibs(1));
console.log(sumFibs(1000));
console.log(sumFibs(4000000));
console.log(sumFibs(75024));
console.log(sumFibs(75025));
</script>
</body>
</html>