Skip to content

Instantly share code, notes, and snippets.

@brettinternet
Last active April 26, 2017 17:04
Show Gist options
  • Save brettinternet/68d6f4bbe85d6e62d0e41bd16b9d5cb6 to your computer and use it in GitHub Desktop.
Save brettinternet/68d6f4bbe85d6e62d0e41bd16b9d5cb6 to your computer and use it in GitHub Desktop.
let fibonacci = (n) => {
if(n <= 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
};
@brettinternet
Copy link
Author

brettinternet commented Apr 13, 2017

While recursion is a viable solution, a while loop is more optimal.

let fibonacci = (num) => {
  let a = 1, b = 0, temp;

  while (num >= 0){
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment