Created
October 17, 2019 09:29
-
-
Save marekdano/21b00d7efb2e78cd5b7bdd18161b7cb2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// write function for fibonacci numbers where | |
// F[1]=F[2]=1; F[3]=2; F[4]=3; => 1,1,2,3,5,8,... | |
const fibRec = n => { | |
if (n === 1 || n === 2) { | |
return 1 | |
} | |
return fibRec(n-1) + fibRec(n-2) | |
} | |
const fibImp = n => { | |
let previous = 1 | |
let prePrevious = 1 | |
let result = 1 | |
if (n < 3) { | |
return result | |
} | |
for(let i = 2; i < n; i++) { | |
result = prePrevious + previous | |
prePrevious = previous | |
previous = result | |
} | |
return result | |
} | |
// TEST | |
console.log(fibImp(1) === 1) | |
console.log(fibImp(2) === 1) | |
console.log(fibImp(4) === 3) | |
console.log(fibImp(100000) === fibImp(99999) + fibImp(99998)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment