Skip to content

Instantly share code, notes, and snippets.

@ufocoder
Last active January 21, 2019 17:36
Show Gist options
  • Save ufocoder/910b5ffb7212ed5d1a1611a4ff79b34e to your computer and use it in GitHub Desktop.
Save ufocoder/910b5ffb7212ed5d1a1611a4ff79b34e to your computer and use it in GitHub Desktop.
const fibonacciRecursive = n => n < 2
? 1
: fibonacciRecursive(n-1) + fibonacciRecursive(n-2)
const fibonacciArray = n => {
let arr = [1, 1]
for (let i = 0; i < n-1; i++) {
arr[i + 2] = arr[i + 1] + arr[i];
}
return arr[n]
}
const fibonacciCycle = n => {
let prevNumber = 1;
let currentNumber = 1;
let nextNumber = 1;
for (let i = 0; i < n-1; i++) {
nextNumber = prevNumber + currentNumber;
prevNumber = currentNumber;
currentNumber = nextNumber;
}
return nextNumber;
}
const testCases = [1, 1, 2, 3, 5, 8, 13, 21, 34]
testCases.forEach((testCase, index) => {
console.assert(testCase === fibonacciRecursive(index))
console.assert(testCase === fibonacciArray(index))
console.assert(testCase === fibonacciCycle(index))
})
@DevYears
Copy link

Один вариант забыл =)
const fibonacciFunc = (n, tmp=Math.sqrt(5)) => (Math.pow((1+tmp)/2, n + 1) - Math.pow((1-tmp)/2, n + 1)) / tmp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment