Hi together
It took me a few days, but I passed the “Sum All Odd Fibonaccis” Challenge.
I have 2 Questions:
1 How good/bad is my code (I think not to bad)?
2 Actually it should be possible to get all Fibonacci Numbers by using Recursion. But can I use Recursion to solve this challenge too? Including just sum the odd Numbers?
Here’s one example with a recursive solution. The function takes the latest two Fibonacci numbers (n and m) and the sum of all odd numbers as parameters.
function sumFibs(num) {
const fibsumRecursion = (n, m, sum) => {
if (m <= num ){ /* as long as the latest number is smaller than num... */
sum = m%2 !== 0 ? sum+m : sum; /* if the latest number is odd, add it to sum */
[n,m] = [m, n+m]; /* use array destructuring to find the next two numbers */
return fibsum(n, m, sum) /* run the function again with new parameters */
} else {
return sum
}
}
return fibsumRecursion(1,1,1) /* initialise with n=1, m=1 --> sum is already 1*/
}
I’m not sure if this is super readable, but it avoids building the whole array of numbers first.