简体   繁体   English

将BigIntegers打印到文本文件

[英]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. 我在Java中计算非常大的因子。但是当我尝试将它们写入文本文件时,它需要花费太多时间。 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! 打印10,000! to a text file takes 194 ms. 到文本文件需要194毫秒。 The file size is 35.7 kB. 文件大小为35.7 kB。

Printing 100,000! 打印100,000! to a text file takes 24,314 ms. 到文本文件需要24,314毫秒。 The file size is 456.6 kB. 文件大小为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? 如何在几秒钟内打印数百万位数的BigIntegers? 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. 您观察到的时间是由BigInteger.toString()引起的,而不是写入文件。

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. 将looong BigInteger转换为十进制(或任何其他基数)数字序列是一个繁琐的过程,涉及基础的looong int []的looong划分,并以相当环境的方式组成结果字符串,甚至使用StringBuilder 。 (I just checked: 1.8 used an improved algorithm, but 35k or 456k digits is still a long way to go.) (我刚刚检查过:1.8使用了改进的算法,但是35k或456k的数字还有很长的路要走。)

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. 我曾经遇到过这个问题并最终编写了我自己的BigInteger,使用的表示法可以非常快速地转换为基数10。

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. 如果您希望频繁/长时间转换为十进制字符串,请尝试找到一个代表基数中10的整数幂的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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