6

I am working on problem n°104 of project Euler Problem 104 and would like to do it in javascript.

In order to solve this problem I need to compute large values of the Fibonacci sequence, but the numbers produced by this sequence are too large to be handle by classic Number, so I'm using BigInt supported in the latest versions of javascript.

Once I've got a particular result stored in a BigInt, I need to check it's 10 first, and last digits.


To get the digits from a Number we usually do something like in the code below, but when the number becomes very large, things go wrong:

let number = BigInt(123456789)
console.log(number.toString())
console.log(number.toString()[3]) // Result is fine

let bigNumber = BigInt(1234567891111111111111111111111111111)
console.log(bigNumber.toString())
console.log(bigNumber.toString()[30]) // unpredictable result

It seems like the "toString()" methods is only using the precision of the Number type (2^53 I believe), thus we are quickly losing precision on the last digits of the BigInt number. The problem is I can't find other methods to extract those digits.

Edit : I need the precision to be perfect because basicaly what i'm doing for example is :

Compute Fibonacci(500) = 280571172992510140037611932413038677189525

Get the 10 last digits of this number : 8677189525 (this is where is lose the precision)

And then to solve my problem I need to check that those 10 last digits contains all the digits from 1 to 9

S. Sylvain
  • 81
  • 6
  • Exactly how precise do you want the numbers to be? Questions typically get better answers when you explicitly state what your desired results are. Also, +1 – Lord Elrond Mar 09 '19 at 00:49

1 Answers1

5

For big numbers, I think you should add the n suffix:

let number = BigInt(123456789)
console.log(number.toString())
console.log(number.toString()[3]) // Result is fine

let bigNumber = 1234567891111111111111111111111111111n // <-- n suffix, literal syntax
console.log(bigNumber.toString())
console.log(bigNumber.toString()[30]) // result

let bigNumber2 = BigInt('1234567891111111111111111111111111111') // <-- also works as a string, in case you can't use the literal for some reason 
console.log(bigNumber2.toString())
console.log(bigNumber2.toString()[30]) // result
Austin Greco
  • 32,997
  • 6
  • 55
  • 59
  • Thank you, it's quite tricky that we can't use the BigInt() initializer without using n or literal but I guess it makes sense – S. Sylvain Mar 09 '19 at 01:02