I am working on a seemingly typical task for an interview - to calculate a Fibonacci number by an index of that number. But the difficulty of the task is that the index can be up to 2000000. I have encountered several problems and I do not understand why they happen.
First the code:
function fib(number) {
const left = Math.pow((1 + Math.sqrt(5)) / 2, number);
const right = Math.pow((1 - Math.sqrt(5)) / 2, number);
const result = Math.round((left - right) / Math.sqrt(5));
console.log(result); //
return BigInt(result); //
}
Problems:
- BigInt differs from a number
fib(96);
console.log(result) // -> 51680708854858490000
BigInt(result) // 51680708854858489856
- Wrong answer. I think it is related to the previous problem
fib(96);
// Must return 51680708854858323072
// But return BigInt 51680708854858489856