Problem 16: Power Digit Sum
215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 21000?
The Catch
How to store and quickly calculate extremely large numbers.
The Light
Use Java's BigInteger class as discussed in Problem 13. Then parse the result into an array of digit-character to calculate their sum.
The Code
import java.math.BigInteger; public class Problem16 { public static void main(String[] args) { BigInteger n = new BigInteger("2"); n = n.pow(1000); System.out.println("2^1000 = " + n); String s = n.toString(); int sum = 0; for(int i = 0; i < s.length(); i++) { sum += Character.getNumericValue(s.charAt(i)); } System.out.println("Sum of all digits = " + sum); } }