console
function recursionFbi(n) {
if (n < 3) return(1);
if (n === 3) return(2);
return recursionFbi(n-1) + recursionFbi(n-2);
}
function circleFbi(n) {
document.getElementById('resStart').innerText = (new Date()).getTime();
if (n < 3) return 1;
let a = 1, b = 1, c = 0;
for (let i = 0; i < n; i++) {
if (i > 1) {
c = a + b;
a = b;
b = c;
}
}
return c;
}
let resn = '';
document.getElementById('input').onchange = function() {
resn = this.value;
}
function btnClick(fun) {
new Promise((resolve, reject) => {
document.getElementById('resStart').innerText = (new Date()).getTime();
resolve(fun(resn));
}).then(res => {
document.getElementById('res').innerText = res;
document.getElementById('resEnd').innerText = (new Date()).getTime();
document.getElementById('resTime').innerText = document.getElementById('resEnd').innerText - document.getElementById('resStart').innerText;
})
}
document.getElementById('btn1').onclick = function() {
btnClick(recursionFbi);
}
document.getElementById('btn2').onclick = function() {
btnClick(circleFbi);
}
<html>
<title>JS数据结构--算法之复杂度判断</title>
<style>
button {
cursor: pointer;
}
</style>
<body>
<p>1、求裴波那契数列第n项的值:</p>
<p>
<input type="text" id="input" value="">
<button id="btn1">递归算法</button>
<button id="btn2">循环算法</button>
</p>
<p>
结果:<span id='res'></span>
</p>
<p>
开始时间戳:<span id='resStart'></span>
</p>
<p>
结束时间戳:<span id='resEnd'></span>
</p>
<p>
耗时:<span id='resTime'></span>
</p>
</body>
</html>