Skip to content

Instantly share code, notes, and snippets.

@vaidehijoshi
Last active October 23, 2017 14:45
Show Gist options
  • Save vaidehijoshi/1fd7415cf36b487586d58dae0f32e3fb to your computer and use it in GitHub Desktop.
Save vaidehijoshi/1fd7415cf36b487586d58dae0f32e3fb to your computer and use it in GitHub Desktop.
// 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