What to do when you need to store a (very) large number?

后端 未结 4 1362
南笙
南笙 2021-01-18 00:55

I am trying to do a Project Euler problem but it involves adding the digits of a very large number. (100!)

Using Java int and long are too small.

Thanks for

4条回答
  •  半阙折子戏
    2021-01-18 01:43

    import java.math.BigInteger;
    import java.util.*;
    
    public class Main {
        protected static ArrayList table = new ArrayList();
    
        static {
            table.add(BigInteger.valueOf(1));
        }
    
        public static synchronized BigInteger factorial(int x) {
            if (x < 0) throw new IllegalArgumentException("x must be non-negative.");
            for (int size = table.size(); size <= x; size++) {
                BigInteger lastfact = table.get(size - 1);
                BigInteger nextfact = lastfact.multiply(BigInteger.valueOf(size));
                table.add(nextfact);
            }
            return table.get(x);
        }
    
        public static void main(String[] args) {
            for (int i = 0; i <= 50; i++)
                System.out.println(i + "! = " + factorial(i));
        }
    }
    

提交回复
热议问题