Skip to content

Instantly share code, notes, and snippets.

@adprocas
Created March 23, 2017 17:00
Show Gist options
  • Save adprocas/d699c645e30699dd3bab61d82a1a4744 to your computer and use it in GitHub Desktop.
Save adprocas/d699c645e30699dd3bab61d82a1a4744 to your computer and use it in GitHub Desktop.
Project Euler Problem 16 - Power digit sum
package com.company.ProjectEuler;
import java.math.BigInteger;
/**
* Created by Adam Leathorn on 23/03/2017.
*/
public class ProjectEulerProblem16
{
public ProjectEulerProblem16() {
int x = 2;
int y = 1000;
String power = calculatePower(x, y).toString();
System.out.println(x + "^"+y+" is:");
System.out.println(power);
System.out.println("The sum of the digits of " + x + "^"+y+" is:");
System.out.println(addDigitsFromString(power));
}
public BigInteger calculatePower(int x, int y) {
BigInteger result = new BigInteger(String.valueOf(x));
BigInteger bigX = new BigInteger(String.valueOf(x));
for(int i = 2; i <= y; i++) {
result = result.multiply(bigX);
}
return result;
}
private long addDigitsFromString(String nums) {
long numbers = 0;
for (int i = 0; i < nums.length(); i++) {
numbers += nums.charAt(i) - '0';
}
return numbers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment