I made a program in Java to calculate extreme factorials like that of 1 milion. What it does essentially is to start a loop from 1 to n
and every iteration, multiply a BigDecimal
with the value of the counter variable in the loop. Once the loop is done, it invokes BigDecimal#toPlainString()
which returns the number produced as a String. The invokation of this method however takes very very long to execute. For example, in the code bellow:
public static void main(String[] args) {
BigDecimal number = new BigDecimal(1);
long startTime = System.currentTimeMillis();
for (int i = 1; i < 500000; i++) {
number = number.multiply(new BigDecimal(i));
}
System.out.println("Generating took: " + (System.currentTimeMillis() - startTime) + "ms. Creating String.");
startTime = System.currentTimeMillis();
String result = number.toPlainString();
System.out.println("String generation took: " + (System.currentTimeMillis() - startTime) + "ms");
FileUtils.writeStringToFile(new File("Path/To/File"), result);
}
the output to console was:
Generating took: 181324ms. Creating String.
String generation took: 710498ms
which demonstrates how long the method toPlainString()
took.
I understand that we are dealing with huge numbers (arround a milion digits in the example above) but i wanted to know if there is any way to speed up this method and how should i go about doing that?
Thanks!
EDIT #1: The only reason why the milisecond time calculations where added in the post is to bring 'long' into prespective, and possibly demonstrate the behaviour of the code in case the problem is not reproducable by all readers. What i am trying to do is determine why it took so long in my case, and most importantly how to speed up the process of converting to String.