0

I am trying to find the first number in the Fibonacci sequence to contain over 1000 digits.

Given a number n (e.g. 4), I found a way to find what place the first number with n-digits has in the Fibonacci sequence as well as a way to find the number given its place in the sequence.

Say, for example, you need to know the first number with 4 digits in the Fibonacci sequence as well as its place in the sequence. My code would work like this:

var phi = (1+Math.sqrt(5))/2;
var nDigits = 4;


var fEntry = Math.ceil(2 + Math.log(Math.pow(10, nDigits- 
1))/Math.log(phi)); 
var fNumber = 2 * Math.pow(phi, fEntry);

console.log(fEntry);
console.log(fNumber);

In the console you would see fEntry (that is, the place the number has in the Fibonacci sequence) and fNumber (the number you're looking for). If you want to find the first number with 4 digits and its place in the sequence, for example, you'll get number 1597 at place 17, which is correct.

So far so good.

Problems arise when I want to find big numbers. I need to find the first number with 1000 digits in the Fibonacci sequence, but when I write nDigits = 1000 and run the code, the console displays "Infinity" for fEntry and for fNumber. I guess the reason is that my code involves calculations with numbers higher than what Javascript can deal with.

How can I find that number and avoid Infinity?

tommsyeah
  • 121
  • 3
  • 10

1 Answers1

0

How can I find that number and avoid Infinity?

You can't, with the number type. Although it can hold massive values, it loses integer accuracy after Number.MAX_SAFE_INTEGER (9,007,199,254,740,991):

const a = Number.MAX_SAFE_INTEGER;
console.log(a);     // 9007199254740991
console.log(a + 1); // 9007199254740992, so far so good
console.log(a + 2); // 9007199254740992, oh dear...

You can use the new BigInt on platforms that support it. Alternately, any of several "big int" libraries that store the numbers as strings of digits (literally).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thank you for you answer. I did a bit of research and, if I understood correctly, I cannot perform operations with numbers larger than Number.MAX_SAFE_INTEGER if I use BigInt or the libraries you mentioned. Do you think there's any way I can perform that large math.pow that is required in order to find the first number with 1000 digits in the Fibonacci sequence? If so, how? – tommsyeah Apr 05 '19 at 16:08
  • @tommsyeah - Yes, you can: `(9007199254740991n + 9007199254740991n + 9007199254740991n + 9007199254740991n) * 10000000000n` is `360287970189639640000000000n`. BigInt has no range limit other than memory, and has all the basic operations. It's true it doesn't have `sqrt`, some functions [need to be implemented](https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root) (at least for now). – T.J. Crowder Apr 05 '19 at 16:20