I was asked to print a list to the console of the Fibonacci sequence up to a given number.
It took me a while to come up with a solution, and I'm happy to have written something that works.
I struggled with trying to incorporate while loop, and ended up using a for loop with an if statement.
I have two questions:
- Is it sensible to try this with a while loop?
- How could one create this sequence without a preset array with the first two numbers in the sequence?
Thank you! By the way, this is my first post to StackOverflow, so any feedback on posting etiquette would be appreciated as well.
function fibbonaciToNum(num) {
let current = 0;
let arr = [0, 1];
for (let i = 1; i < arr.length; i++) {
current = arr[i] + arr[i - 1]
if (current <= num) {
arr.push(current);
}
}
return arr;
}
console.log(fibbonaciToNum(34));
Aucun commentaire:
Enregistrer un commentaire