0

I am trying to compare numbers that are so large that even BigIntegers cannot deal with them. My solution is to convert the numbers to Strings and use String comparison on them.

Will this work? I am not really sure how to implement something like this. I am just attempting to unit test an algorithm to produce the factorial of 1000 for a project Euler program that I am sucked into.

5
  • Do you have some sample code for BigIntegers, which aren't comparable? And why shouldn't it work with Strings? If only one String starts with "-", this is smaller. If both are positive, the shorter String is smaller, if both negative the longer one. Else compare them digit by digit from the left. Commented Sep 27, 2011 at 0:44
  • How big are your numbers? 1000! seems to have about 2568 digits, which should not be a problem Commented Sep 27, 2011 at 0:45
  • The largest number would be 1000!, yes.Will BigInteger expand to meet requirements? Commented Sep 27, 2011 at 0:52
  • The number isn't that big, only 2568 decimal digits. Check it at Wolfram Alpha Commented Sep 27, 2011 at 4:27
  • Since a number would use more space as a string than as a BigInteger, the latter can handle larger numbers. Unless you have a really large machine (>>8GB RAM) it is only limited by available memory. Commented Sep 30, 2011 at 10:48

1 Answer 1

1

Your assumption is wrong.

BigInteger provides arbitrary precision, so it can definitely deal with numbers this big.

Try the following:

public class Main {
    public static void main(String[] args) {
        BigInteger thousand = BigInteger.valueOf(1000L);
        for (int i = 999; i > 0; i--)
        {
            thousand = thousand.multiply(BigInteger.valueOf(i));
        }

        System.out.println(thousand.toString());
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Really? I had read the upper limit of BigInteger was much smaller than this. You say the limit is arbitrary, does it expand to meet user needs? Do you think this would be the best way to test my code?
BigInteger encodes integers using sign-magnitude encoding (en.wikipedia.org/wiki/…) with an int[] to store the magnitude. The maximum length of an array in Java is 2147483647. That's pretty big (unless my math is wrong, it's around 2^(32*2147483647).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.