开发者

Converting large numbers to String format for comparison

开发者 https://www.devze.com 2023-04-08 01:58 出处:网络
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.

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 algorith开发者_JAVA技巧m to produce the factorial of 1000 for a project Euler program that I am sucked into.


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

}
0

精彩评论

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

关注公众号