Decimal expansion program running very slow for large inputs

可紊 提交于 2019-12-10 13:58:51

问题


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());
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/15176872/decimal-expansion-program-running-very-slow-for-large-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!