function fibo() {
var first,second,add;
for(var i=0;i<4000;i++){
if(i === 0){
first = 1;
second = 2;
}
add = first + second;
first
You can use WebWorkers and BigInt to calculate huge values of the fibonacci sequence:
var input = document.querySelector('input');
var output = document.querySelector('#output');
var fulloutput = document.querySelector('#fulloutput');
var time = document.querySelector('#time');
var start, end;
var worker;
var createWorker = function () {
if (worker) worker.terminate();
var workerContent = "self.onmessage = " + workerFunction.toString();
var blob = new Blob([workerContent], {type: 'application/javascript'});
worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = receive;
};
var workerFunction = function(event) {
var total = BigInt(event.data);
var fib = function(index) {
var temp;
var last = BigInt(0);
var sum = BigInt(1);
for (; index >= BigInt(2); index--) {
if (index % BigInt(1000) === BigInt(0))
self.postMessage({
total: total,
calculating: index
});
temp = last;
last = sum;
sum += temp;
}
return sum;
};
if (total > BigInt(0)) self.postMessage({done: fib(total)});
else self.postMessage({error: 'Input error'});
};
window.addEventListener('load', function () {
if (!window.Worker ||
!window.Blob ||
!window.URL ||
!window.BigInt) {
output.textContent = 'Browser not supported';
} else {
start = performance.now();
createWorker();
output.textContent = 'Worker created, starting calculations';
worker.postMessage(input.value);
input.addEventListener('change', function () {
createWorker();
start = performance.now();
output.textContent = 'Calculating';
worker.postMessage(input.value);
});
}
});
var receive = function(event) {
if (event.data.error) {
output.textContent = event.data.error;
}
if (event.data.calculating) {
var total = BigInt(event.data.total);
var index = BigInt(event.data.calculating);
var progress = (BigInt(100) * (total - index) / total);
output.textContent = 'Calculating ' + progress + '%';
}
if (event.data.done) {
var formatter = new Intl.NumberFormat('en', {
notation: 'scientific'
});
output.textContent = formatter.format(event.data.done);
fulloutput.textContent = event.data.done;
end = performance.now();
time.textContent = 'It took ' + ((end - start) / 1000) + ' seconds';
}
};
body {
display: grid;
place-content: center;
min-height: 100vh;
}
p, pre {
text-align: center;
width: 80vw;
white-space:normal;
word-wrap: break-word;
}
N: