function sumFibs(num) {
let sum = 0;
for (let i = 0; i < num.length; i++){
if (num % 2 == 0) {
} else if (num % 2 == 1){
sum = num + num
}
}
return sum;
}
//Fibonacci sequence is to add first two numbers, answer takes up next spot, then repeat
console.log(sumFibs(4));
Need help. Need to find a way to tell them to add all the odd numbers in the sequence. Do I need to write a line of code to tell them what the sequence is? Or is the Fibonacci sequence already known for this problem?
It looks like youāve got the correct logical flow. But you need to keep running that logic, until a condition is met that tells your code to stop. Do you know the syntax for something like that? (Thereās a few options here)
how about you try to put them in more āobviousā way, and see if you can spot that sequence going more easily, here is an example of first āsevenā numbers from āfibonacci seriesā
function sumFibs(num) {
let prevNumber = 0;
let currNumber = 1;
let result = 0;
// before number reaches num
while (currNumber <= num) {
// if that number is odd
if (currNumber % 2 == 1) {
// then those odd numbers to the result [1+1+3] = 5
result += currNumber;
} // let them know how the Fibonacci sequence works
currNumber += prevNumber;// 1 = 0 + 1 aka 0 + 1 = 1
prevNumber = currNumber - prevNumber; // 0 = 1 - 0; letting them know what the previous number is creating the cycle/pattern
}
return result;
}
sumFibs(4);
I always get a little confused when I see a big jump in the complexity of your solution relative to your described plan, but this is a clever trick here.
This is great! The other common solution pattern is a functional approach using array methods. Something like this:
getAllFibsLte(num)
.filter(isOdd)
.reduce(sum)
(youād need to implement the getAllFibsLte, isOdd and sum functions).
The trade-off compared to your imperative solution is reduced performance due to higher memory consumption and more loops, but is arguably more legible (it reads like the English instructions).