2

I'm trying to solve Project Euler #16:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 2^1000?

question looks simple but Instead of using modulus 10 I tried to solve the question like this:

public class Main {

    public static void main(String[] args) {


      long number = (long) Math.pow(2,100);

      long sum=0;

      String number2 = String.valueOf(number);

      char[] digits = number2.toCharArray();

      for (char digit : digits) {

        sum = sum + digit;
      }

      System.out.println(sum);



    }


}

However it gives a wrong answer, I can't see my mistake, Isn't it possible to solve this question with this way?

Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85
  • 1
    2^100 won't fit into long, you need to look into BigInt types – Oleg Bogdanov Dec 31 '16 at 08:33
  • But I cant cast `Math.pow(2,100)`to BigInteger? – Ege Kuzubasioglu Dec 31 '16 at 08:35
  • yes you cant, but pow is just a multiplication after all – Oleg Bogdanov Dec 31 '16 at 08:38
  • 1
    Aside from the storage limits of a long, you might also want to look at how you're adding your digits. As you have it, you're adding the ASCII values of each digit of the number. You should try subtracting 48 from each digit before adding it to the total to get its numeric value. –  Dec 31 '16 at 09:09
  • 1
    @Andrevin, better use `Character.getNumericValue()` or `Character.digit()`. ASCII arithmetic is so low-level. – Ole V.V. Dec 31 '16 at 09:50

1 Answers1

3

A long cannot hold the number. You must rewrite using a datatype that can.

See Large Numbers in Java for pointers.

Community
  • 1
  • 1
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347