Tuesday, March 3, 2015

JavaScript: Too Many Bits

The solution to the 16th question posed by the Project Euler website requires a user to parse through a number that is over 300 digits long.

Problem: I need to access each digit in the number. My algorithm returned a value in scientific notation and attempts to retrieve all digits of the number failed as most methods, such as .toPrecision are limited to about 20 digits of precision.

Cause: JavaScript numbers only have 64 bits to use for storage (my number is 1001 bits)

Solution: Use the BigInt.js library, created by Leemon Baird.


I found a calculator that could compute my number and display all the digits using the BigInt.js library and therefore trusted it over other big integer libraries to handle the sizable number in my program. After unsuccessful attempts with the new operator I reread the documentation until I found out how to create a bigInt from a string using the str2bigInt function. Only concern is that this asked for how many bits the number needed, after exploring binary I had a better grasp on why each digit needs about 3 bits, and declared the numbers accordingly. At long last I updated my simple algorithm and submitted the solution.

"Congratulations, the answer you gave to problem 16 is correct.

You are the 127007th person to have solved this problem". . and successfully submit it to the Project Euler website.

No comments:

Post a Comment