Created
August 3, 2013 06:37
-
-
Save blessdyb/6145472 to your computer and use it in GitHub Desktop.
3 methods for get fibonacci list element
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
#!/usr/bin/env node | |
/* | |
use node fibonacci num in terminal to get fibonacci list element | |
*/ | |
var fibonacci1 = function(n) { | |
if (n < 1) { | |
return 0; | |
} else if (n === 1 || n ===2) { | |
return 1; | |
} else if (n > 2) { | |
return fibonacci1(n - 1) + fibonacci1(n - 2); | |
} | |
}; | |
var fibonacci2 = function(n) { | |
var ret = 0, | |
f0 = 0, | |
f1 = 1, | |
i = 0; | |
for(; i <= n; i++) { | |
ret += f0; | |
f0 = f1; | |
f1 = ret; | |
} | |
return ret; | |
}; | |
var fibonacci3 = function(n) { | |
var phi = (1 + Math.sqrt(5)) / 2; | |
return Math.round((Math.pow(phi, n) - Math.pow(1 - phi, n)) / Math.sqrt(5)); | |
}; | |
var num = process.argv[2] || 1; | |
var time = process.hrtime(); | |
console.log(fibonacci1(num)); | |
console.log(process.hrtime(time)[0] + 's'); | |
time = process.hrtime(); | |
console.log(fibonacci2(num)); | |
console.log(process.hrtime(time)[0] + 's'); | |
time = process.hrtime(); | |
console.log(fibonacci3(num)); | |
console.log(process.hrtime(time)[0] + 's'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment