在数字因子分解中使用BigDecimal

时间:2014-09-16 21:48:42

标签: java bigdecimal

我想在java中归档数字因子分解,但在尝试运行程序时遇到错误。我也得到了不可思议的结果,但我确信这应该有效。

以下是我的代码

  import java.math.*;

public class FactorizerBig{
    private BigDecimal input;
    FactorizerBig(BigDecimal x){
    input = x;
    }
    public void processBig(){//main algorithm
    String s = "";
    MathContext mc = new MathContext(2); // 2 precision
    BigDecimal idx = new BigDecimal("2");
    BigDecimal z = new BigDecimal("0");
    while((idx.compareTo(input)) == -1 || (idx.compareTo(input)) == 0 ){
        int comp =  (input.remainder(idx,mc)).compareTo(z);
        if(comp != 0){
        idx = idx.add(idx);
        }else{ 
        s = s.concat(" * "+idx);
        input = input.divide(idx);
        idx = new BigDecimal("2");
        }

    }

    System.out.println(s.substring(2));
    }
}

这就是我得到的输出

javac FactorizerBig.java Test.java && java Test
12
 2 * 2
23
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -2
    at java.lang.String.substring(String.java:1875)
    at FactorizerBig.processBig(FactorizerBig.java:25)
    at Test.main(Test.java:10)

1 个答案:

答案 0 :(得分:1)

您已将i++转换为idx = idx.add(idx),这意味着i = i + i

使用 idx = idx.add(BigDecimal.ONE)

顺便说一句,您也可以将i <= input替换为(idx.compareTo(input)) < 1

import java.math.*;

public class FactorizerBig {
    private BigDecimal input;

    FactorizerBig(BigDecimal x) {
        input = x;
    }

    public void processBig() {//main algorithm
        String s = "";
        MathContext mc = new MathContext(2); // 2 precision
        BigDecimal idx = new BigDecimal("2");
        BigDecimal z = new BigDecimal("0");
        while ((idx.compareTo(input)) < 1) {
            int comp = (input.remainder(idx, mc)).compareTo(z);
            if (comp != 0) {
                idx = idx.add(BigDecimal.ONE);
            } else {
                s = s.concat(" * " + idx);
                input = input.divide(idx);
                idx = new BigDecimal("2");
            }

        }

        System.out.println(s.substring(2));
    }
}