Search code examples
javastringtostringgmp

How can this method be changed to return a List of Strings rather than a String?


Recently I begun using GMP in Java through a wrapper (From this Github repo) for some calculations involving extreme numbers.
By 'extreme', I mean numbers sometimes with more than 700 milion digits.

Everything is working absolutely fine, but one calculation I am planing to make is estimated to produce a number with about 8 bilion digits and although the GMP library can handle that and the machine which will execute the code has more than enough memory, the problem is that the only way of getting this number in base 10 is through the method toString(int base) (or simply toString()) which returns a String containing the number at the specified base, but since a String relies on a char array to hold the letters, it will not be able to hold 8 bilion letters since the max array size is arround 2^32-6 if I'm not mistaken.

Unfortunately appart from Java I dont know any other language well enough...

Therefore my question is, how can the GMP wrapper (and possibly native code) be changed in order to return a List<String> rather than a single String with the digits? And if this is too hard or even impossible, is there any other alternative I have in Java to deal with numbers that large?

Thank you!


Solution

  • I don't know the type of the number, so assuming BigInteger. Try this.

    UPDATE: created the variable DIGITS_PER_STRNG, so you can control the number of digits per one String item.

    class Sample {
    
        private static void test_num_to_string() {
            List<String> list = intToStringList(sampleBigInt());
        }
    
        private static final int DIGITS_PER_STRNG = 10; // DIGITS_PER_STRNG < Integer.MAX_VALUE ( = max String length)
        private static final BigInteger DIVIDER = BigInteger.valueOf(10);
    
        private static List<String> intToStringList(BigInteger i) {
            List list = new ArrayList();
    
            while (i.compareTo(BigInteger.ZERO) > 0) {
                String str = "";
                for (int j = 0; j < DIGITS_PER_STRNG; j ++) {
                    BigInteger[] divideAndRemainder = i.divideAndRemainder(DIVIDER);
                    str = str + String.valueOf(divideAndRemainder[1]);
                    i = divideAndRemainder[0];
                }
                list.add(str);
                System.out.println(str);
            }
    
            return list;
        }
    
        private static BigInteger sampleBigInt() {
            BigInteger bigInt = BigInteger.valueOf((int) Math.pow(2, 10000));
            int i;
            for (i = 0; i < 10; i ++) {
                bigInt = bigInt.multiply(bigInt);
            }
            return bigInt;
        }
    }