How can I quickly load a large txt file into BigInteger?

后端 未结 3 2004
南笙
南笙 2020-12-04 02:06

I\'m importing a large text file, 17 million digits long and I\'m using this code:

BufferedReader reader = new BufferedReader(new FileReader(\"test2         


        
相关标签:
3条回答
  • 2020-12-04 02:35

    It is slow because new BigInteger(String) is doing radix conversion from decimal to binary, which is O(N2). Nothing you can do about that.

    You could save either the object itself, via Serialization, or the byte array it is stored in, via BigInteger.toByteArray(). Either will load essentially instanteously.

    0 讨论(0)
  • 2020-12-04 02:35

    As the comments have indicated, your code is slow because you're attempting to load a number with a lot of digits.

    If you're unsatisfied with the performance of Java's BigInteger implementation, then I suggest you look elsewhere.

    This library claims to have a BigInteger that outperforms Java's implementation (note it may not speed up loading the number, but it should improve multiplication and division performance).

    0 讨论(0)
  • 2020-12-04 02:42

    As an optimization, since BigInteger is Serializable, you could save it to a binary file once and speed up your loading considerably.

    Loading a serialized object should be way faster than parsing a huge string everytime.

    Use ObjectOutputStream to save your big integer and ObjectInputStream to read it back in.

    0 讨论(0)
提交回复
热议问题