I am writing a program to calculate the decimal expansion on the number 103993/33102
and I want to print out all of the trailing decimals depending on what number the user inputs. It runs quickly for all number up to 10^5
but if input 10^6
to program takes around 5 minutes to print out an answer. How can I speed things up? I have tried two different approaches one using BigDecimal
and the other using strings and neither one is working efficiently.
public static void main(String[] args) throws NumberFormatException,
IOException {
// BigDecimal num1 = new BigDecimal(103993);
// BigDecimal num2 = new BigDecimal(33102);
String repNum = "415926530119026040722614947737296840070086399613316";
// pw.println(num.toString());
String sNum = "3.1";
// pw.println(repNum.length());
int cases = Integer.parseInt(br.readLine());
int dec;
for (int i = 0; i < cases; i++) {
sNum = "3.1";
dec = Integer.parseInt(br.readLine());
if (dec == 0)
pw.println("3");
else if (dec <= 52) {
sNum += repNum.substring(0, dec - 1);
pw.println(sNum);
} else {
while (dec > 52) {
sNum += repNum;
dec -= 51;
}
sNum += repNum.substring(0, dec - 1);
pw.println(sNum);
}
// pw.println(num1.divide(num2, dec,
// RoundingMode.FLOOR).toString());
}
}
Instead of creating a long string of digits just print out the digits. For example:
while (dec > 52) {
System.out.print(repNum);
dec -= 51;
}
pw.println(repNum.substring(0, dec - 1));
Creating a long string in a loop by concatenating is really bad for performance because strings are immutable. The program spends all its time creating new strings, one longer than the other, and copying characters from the old to the new, essentially implementing Schlemiel the Painter's algorithm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With