Digit Summation BigInteger

I am trying to find the sum of the digits of a number 2 ^ 1000, and for this I am using the Java class BigInteger. However, I could not make it real. In the end, I get 0 (zero) with the following code. What could be the problem?

Thank...


After Kon's help, I fixed the problem, but this time I get the wrong result. Can anyone see a problem with the algorithm?

public static void main(String []args) throws Exception
{
    BigInteger big = BigInteger.valueOf(2).pow(1000);
    BigInteger big2 = BigInteger.valueOf(0);


    //System.out.println(big);

    for(long i = 1; i<283; i++)
    {
         big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));
    }

    System.out.println(big2);
}
+4
source share
2 answers

BigInteger - , . , String .

BigInteger big = BigInteger.valueOf(2).pow(1000);
String digits = big.toString();
int sum = 0;

for(int i = 0; i < digits.length(); i++) {
    int digit = (int) (digits.charAt(i) - '0');
    sum = sum + digit;
}

System.out.println(sum);
+3

BigInteger , .

big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));

big2 = big2.add(big.mod(BigInteger.valueOf((long) Math.pow(10,i))).divide(BigInteger.valueOf((long)Math.pow(10,i-1))));

Java . .

, , - . BigInteger 2 ^ 1000. , , - big.toString().length().

+1

Source: https://habr.com/ru/post/1530774/


All Articles