views:

273

answers:

1

I'm making a project concerned big numbers 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

A: 

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.

Bill the Lizard