# Java solution to Project Euler Problem 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?

Running time: 5ms

Assessment: Easy and fast using arbitrary-precision arithmetic.

import java.math.BigInteger;

public class Problem016
{
private static int calcDigits(String s)
{
int sum = 0;

for (int i = 0; i < s.length(); i++)
{
Character c = new Character(s.charAt(i));
String z = c.toString();
int j = Integer.parseInt(z);
sum += j;
}

return sum;
}

public static void main(String[] args)
{
long begin = System.currentTimeMillis();

BigInteger n = BigInteger.valueOf(2);
n = n.pow(1000);
System.out.println(calcDigits(n.toString()));

long end = System.currentTimeMillis();
System.out.println(end - begin + "ms");
}
}

## 4 thoughts on “Java solution to Project Euler Problem 16”

1. Asdf says:

I took some of what you did and optimized it a bit, 4ms for me! haha

import java.math.BigInteger;
public class problem16 {
Â Â Â  public static void main(String[]args){
Â Â Â  Â Â Â  long begin = System.currentTimeMillis();
Â Â Â  Â Â Â  BigInteger x = BigInteger.valueOf(2);
Â Â Â  Â Â Â  BigInteger sum = BigInteger.valueOf(0);
Â Â Â  Â Â Â  BigInteger dig = BigInteger.valueOf(0);
Â Â Â  Â Â Â  BigInteger div = BigInteger.valueOf(10);
Â Â Â  Â Â Â  x = x.pow(1000);
Â Â Â  Â Â Â  String s2 = String.valueOf(x);
Â Â Â  Â Â Â  for(int i=0;i<=s2.length();i++){
Â Â Â  Â Â Â  Â Â Â  dig=x.remainder(div);
Â Â Â  Â Â Â  Â Â Â  sum=sum.add(dig);
Â Â Â  Â Â Â  Â Â Â  x=x.divide(div);
Â Â Â  Â Â Â  }
Â Â Â  Â Â Â  System.out.println(sum);
Â Â Â  Â Â Â  long end = System.currentTimeMillis();
Â Â Â  Â Â Â  System.out.println(end – begin + "ms");
Â Â Â  }
}

2. mjhay tejano says:

mark james

3. UmangKedia says:

public class Prob16 {

public static void main(String[] args) {

long begin = System.currentTimeMillis();

long ans=0;
char a[]= new char [1000];
BigInteger two= new BigInteger(“2”);

a= two.pow(1000).toString().toCharArray();

for(int i=0;i<a.length;i++)
{
ans+= a[i]-'0';
}

System.out.println(ans);
long end = System.currentTimeMillis();
System.out.println(end – begin + "ms");

}

}
0ms for me :P :P

4. DalerAsrorov says:

Good One! The only thing I used from this code is digitToStr = String.valueOf(digit)… So,

import java.lang.Math;
import java.math.BigInteger;
public class PowerDigitSum
{
public static void main(String [] args)
{
char let;
String digitToStr = “”;
int sum = 0, len =0, getInt = 0;
BigInteger digit = BigInteger.valueOf(2);
digit = digit.pow(1000);
digitToStr = String.valueOf(digit);
len = digitToStr.length();
for (int i = 0; i<len; i++)
{
let = digitToStr.charAt(i);
getInt = let – 48;//easy way to convert from char to int
sum +=getInt;
}
System.out.println("The digit: " + digit);
System.out.println("The sum of the digits: " + sum);
}
}