开发者

how java.bigInteger valueOf works?

开发者 https://www.devze.com 2022-12-17 17:40 出处:网络
I\'m making a project concerned big number开发者_如何学Pythons without BigInteger, BigDecimal etc. I\'ve managed to do all the basics but now I need to add ability to count factorials. My BigNumber st

I'm making a project concerned big number开发者_如何学Pythons without BigInteger, BigDecimal etc. I've managed to do all the basics but now I need to add ability to count factorials. My BigNumber stores data as int[] .

Here's a sample solution with BigInteger but I can't use it without having the actual value of my number.

    BigInteger n = BigInteger.ONE;
    for (int i=1; i<=20; i++) {
        n = n.multiply(BigInteger.valueOf(i));
        System.out.println(i + "! = " + n);
    }

So how to count the value ? Add ints from last to first, multiplying tens by 10, hundreds by 100 and so on and so on and store it as long ?

Source of BigInteger : http://developer.classpath.org/doc/java/math/BigInteger-source.html


So how to count the value ? Add ints from last to first, multiplying tens by 10, hundreds by 100 and so on and so on and store it as long ?

I don't think storing it as a long is what you intend. What would happen if the value gets bigger than Long.MAX_VALUE?

If n is a BigInteger, then n.multiply(BigInteger.valueOf(i)); should return a BigInteger object. The multiply method should know how to do multiplication with two BigInteger objects without needing to convert them to long. One way of doing that is to loop through each digit using the multiply-and-carry algorithm that we learned in grade school. This will be pretty slow if your values are astronomical, but it does have the benefit of being easy to understand and implement.

0

精彩评论

暂无评论...
验证码 换一张
取 消