Created
July 10, 2019 06:44
-
-
Save JackyYin/f4ba59ebe973472c320b4b4bb6edb8c1 to your computer and use it in GitHub Desktop.
recursion v.s. iteration
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
const recursion = n => { | |
if (n === 0) return 0; | |
if (n === 1) return 1; | |
return recursion(n - 1) + recursion(n - 2); | |
}; | |
const iteration = n => { | |
if (n === 0) return 0; | |
if (n === 1) return 1; | |
let prev = 0; | |
let cur = 1; | |
let newCur; | |
for (let i = 2; i < n + 1; i++ ) { | |
newCur = prev + cur; | |
prev = cur; | |
cur = newCur; | |
} | |
return cur; | |
}; | |
const test = input => { | |
let start; | |
let time; | |
start = Date.now(); | |
recursion(input); | |
time = Date.now() - start; | |
console.log(time); | |
start = Date.now(); | |
iteration(input); | |
time = Date.now() - start; | |
console.log(time); | |
} | |
test(45); | |
// 13392 | |
// 0 | |
test(46); | |
// 21487 | |
// 2 | |
test(47); | |
// 34554 | |
// 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment