Last active
October 23, 2017 14:45
-
-
Save vaidehijoshi/1fd7415cf36b487586d58dae0f32e3fb to your computer and use it in GitHub Desktop.
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
// Calculates the nth number in the Fibonacci sequence. | |
// For example, fibonacci(6) will return the 6th number | |
// in the sequence, or the number 8. | |
function fibonacci(n) { | |
if (n < 2) { | |
// If the nth number is less | |
// than 2, return it directly. | |
console.log('calculating ' + n); | |
return n; | |
} else { | |
// Otherwise, calculate it recursively. | |
console.log('calculating ' + fibonacci(n-1)); | |
console.log('also calculating ' + fibonacci(n-2)); | |
return fibonacci(n-1) + fibonacci(n-2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment