Created
December 19, 2023 12:45
-
-
Save CodeLeom/cadf8078d6214cd401514f0e9ec56bcf to your computer and use it in GitHub Desktop.
Fibonacci Sequence Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//this is a function that generates a fibonacci sequence from any given number. | |
/* | |
A Fibonacci sequence works with adding the last number to the first number to generate the next number. the first numbers is always | |
0, 1 but sometimes, you might be asked to start from 1. Therefore, if you start from 0, 1, the next number will be 0 + 1 = 1 | |
that gives you 0, 1, 1 as the sequence. | |
*/ | |
function fibonacciSeq(n) { | |
var result = []; //an empty array for output | |
if (n === 1) { | |
result = [0]; //this is a template that says, if the input number into the function is 1, then return 0 as the output | |
} else if (n === 2) { | |
result = [0, 1]; //therefore, if 2 is passed as the parameter to the function, then return 0, 1 | |
} else { | |
result = [0, 1] | |
for (var x = 2; x < n; x++){ | |
result.push(result[result.length - 2] + result[result.length - 1]) // this loop now takes any given number, add the last number in the array to the number before the last number | |
} | |
} | |
return result; | |
} | |
result = fibonacciSeq(5) //this is a test number, to generate a Fibonacci sequence for 5 | |
console.log(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment