简体   繁体   中英

Printing BigIntegers to text files

I am calculating very big factorials in Java.However when I try to write them to text files it takes too much time. I'm using this method to print the numbers.

PrintWriter writer = new PrintWriter(index + "!.txt", "UTF-8");
writer.println(number);
writer.close();

Printing 10,000! to a text file takes 194 ms. The file size is 35.7 kB.

Printing 100,000! to a text file takes 24,314 ms. The file size is 456.6 kB.

I think the speed is too slow with this file size. How can I print BigIntegers with millions of digits in a few seconds? Are there faster methods or any way I can optimize this?

The time you observe is due to BigInteger.toString(), not the writing to the file.

Conversion of a looong BigInteger to a sequence of decimal (or any other base) digits is a cumbersome process, involving a looong division of a looong int[] by the base and composing the result string in a rather circumstantial way, even using a StringBuilder. (I just checked: 1.8 used an improved algorithm, but 35k or 456k digits is still a long way to go.)

I ran into this problem once and ended up writing my own BigInteger, using a representation that can be converted to base 10 very quickly.

If you opt for another library, make sure it permits operations that modify an object (rather than return a new object). If you expect frequent/long conversions to decimal string, try to find one that represents the numbers in a base that is an integral power of 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM