Last active
May 17, 2016 01:25
-
-
Save TheIronDev/8e4d356c0881ea0067ac3c414af06a82 to your computer and use it in GitHub Desktop.
Comparing times of getting fibonacci number with different method
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
function fibo(n) { | |
if (n <= 1) return n; | |
return fibo(n-1) + fibo(n-2); | |
} | |
function tailFibo(n, tail) { | |
if (n <= 1) return n; | |
if (tail[n]) return tail[n]; | |
tail[n] = tailFibo(n-1, tail) + tailFibo(n-2, tail); | |
return tail[n]; | |
} | |
function itrFibo(n) { | |
var prev = 0, cur = 1, total = 0, temp; | |
while(n--) { | |
prev = cur; | |
temp = total; | |
total += cur; | |
cur = temp; | |
} | |
return total; | |
} | |
function testAllThree(n) { | |
var results = {}, time; | |
time = Date.now(); | |
fibo(n); | |
results.fibo = Date.now() - time; | |
time = Date.now(); | |
tailFibo(n, {}); | |
results.tailFibo = Date.now() - time; | |
time = Date.now(); | |
itrFibo(n); | |
results.itrFibo = Date.now() - time; | |
return results; | |
} | |
testAllThree(30); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment