养兔子Fibo函数优化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var month = prompt("请输入月数:")
function fibobo(x) {
var arr = [1, 1];
(function fib(n) {
if (n === 0 || n === 1) {
return 1;
}
if (!arr[n]) {
arr.push(fib(n - 1) + fib(n - 2));
return arr[n];
} else {
return arr[n];
}
})(x);
return arr[x - 1];
}
console.time('优化后方案')
console.log(month+"个月后有"+fibobo(month)+"只兔子");
console.timeEnd('优化后方案')
function fib(n) {
if (n<=2){
return 1 ;
}
return fib(n -1 ) + fib(n - 2);
}
console.time('优化前方案')
console.log(month+"个月后有"+fib(month)+"只兔子");
console.timeEnd('优化前方案');
</script>
</body>
</html>
一混五六年

浙公网安备 33010602011771号