Skip to content

Instantly share code, notes, and snippets.

@guxuerui
Last active June 22, 2020 09:16
Show Gist options
  • Save guxuerui/ab79d1c08884f2293d9918d889ec4927 to your computer and use it in GitHub Desktop.
Save guxuerui/ab79d1c08884f2293d9918d889ec4927 to your computer and use it in GitHub Desktop.
菲波那切数列
// const fib = (num) => {
// if (num <= 0) return 0;
// if (num === 1 || num === 2) return 1;
// if (num > 2) {
// let prev = 1, next = 1;
// for (let i = 3; i <= num; i++) {
// let sum = prev + next;
// prev = next;
// next = sum;
// }
// return next;
// }
// };
let map = {
0: 0,
1: 1
};
const fib = (num) => {
if (map[num] === undefined) map[num] = fib(num - 1) + fib(num - 2);
return map[num];
};
@mactanxin
Copy link

fib = n => {
  if (typeof n !== "number") {
     throw new Error("..");
   }
  if (n < 2) {
     return n;
   }
  let a = 0;
  let b = 1;
  while (n--) {
    [a, b] = [b, a + b];
  }
  return a;
};

@guxuerui
Copy link
Author

膜拜大佬👏

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