Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:15
Show Gist options
  • Save dmnugent80/9ddaec944bdd35c16f0a to your computer and use it in GitHub Desktop.
Save dmnugent80/9ddaec944bdd35c16f0a to your computer and use it in GitHub Desktop.
Power Digit Sum
import java.math.BigInteger; // header stuff MUST go above the first class
// our main class becomes a file but the main method is still found
public class PowerDigitSum
{
public static void main(String[] args)
{
BigInteger bigPow = pow(2, 1000);
System.out.println("power: " + bigPow);
String str = bigPow.toString();
System.out.println("string length: " + str.length());
long sum = 0;
for (int i = 0; i < str.length(); i++){
sum += Long.valueOf(Character.getNumericValue(str.charAt(i)));
}
System.out.println("sum: " + sum);
}
public static BigInteger pow(long x, long n){
long mid;
BigInteger temp = BigInteger.ZERO;
if (n == 0){
return BigInteger.ONE;
}
if (n == 1){
return BigInteger.valueOf(x);
}
mid = n / 2;
temp = pow(x, mid);
if (n%2 == 0){
return (temp.multiply(temp));
}
else{
return (BigInteger.valueOf(x).multiply(temp).multiply(temp));
}
}
}
/*output:
power: 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
string length: 302
sum: 1366
*/
//Another implementation:
import java.math.BigInteger;
public class euler16 {
public static void main(String[] args) {
BigInteger b1,b2;
b1= BigInteger.valueOf(1);
b2= BigInteger.valueOf(2);
for (int i=0;i<1000 ;i++ ) {
b1=b1.multiply(b2);
}
String s= null;
s= b1.toString(10);
int sum=0;
for (int j=0;j<s.length() ;j++ ) {
sum=sum+((int)s.charAt(j)-48);
}
System.out.println(sum);
}
}
//And another:
import java.math.BigInteger;
public class PowerDigitSum {
public static void main(String[] args) {
BigInteger bint = new BigInteger("2");
bint = bint.pow(1000);
String x = bint.toString();
long sum = 0;
for (int i = 0; i < x.length(); i++) {
sum += Integer.parseInt(x.substring(i, i + 1));
}
System.out.println(sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment