Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal expansion program running very slow for large inputs

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());
    }
}
like image 663
Will Jamieson Avatar asked Nov 03 '22 03:11

Will Jamieson


1 Answers

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.

like image 118
Joni Avatar answered Nov 14 '22 22:11

Joni