Problem 56
Powerful Digit Sum
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b < 100, what is the maximum digital sum?
幂的数字和
一古戈尔(10100)是一个巨大的数字:一后面跟着一百个零。100100则更是无法想像地巨大:一后面跟着两百个零。然而,尽管这两个数如此巨大,各位数字和却都只有1。
若a, b < 100,所有能表示为ab的自然数中,最大的各位数字和是多少?
package projecteuler;
import java.util.Arrays;
import junit.framework.TestCase;
public class Prj56 extends TestCase {
/**
*
*/
public void testPowerfulDigitSum() {
int maxSum = 0;
int maxA = 0;
int maxB = 0;
int bits = getBits(100, 100);
for (int a = 2; a < 100; a++) {
for (int b = 1; b < 100; b++) {
int[] a1 = enLarge(int2Arr(a), bits);
a1 = power(a1, a, b);
if (sumArr(a1) > maxSum) {
maxSum = sumArr(a1);
maxA = a;
maxB = b;
}
}
}
String fstr = "maxSum=%d,a=%d,b=%d";
fstr = String.format(fstr, maxSum, maxA, maxB);
System.out.println(fstr);
}
public int sumArr(int[] a) {
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
public int getBits(int a, int b) {
return (int) Math.ceil(Math.log(a) / Math.log(10) * b);
}
public int[] power(int[] arr, int multiplier, int b) {
int[] ret = Arrays.copyOf(arr, arr.length);
int count = b;
while (count > 1) {
ret = multiply(ret, multiplier);
count--;
}
return ret;
}
public int[] multiply(int[] arr, int b) {
int[] ret = Arrays.copyOf(arr, arr.length);
for (int i = 0; i < arr.length; i++) {
ret[i] *= b;
}
for (int i = arr.length - 1; i > 0; i--) {
ret[i - 1] = ret[i - 1] + ret[i] / 10;
ret[i] = ret[i] % 10;
}
return ret;
}
public int[] int2Arr(int val) {
String str = Integer.toString(val, 10);
int[] ret = new int[str.length()];
for (int i = 0; i < ret.length; i++) {
ret[i] = Integer.parseInt(String.valueOf(str.charAt(i)));
}
return ret;
}
public int[] enLarge(int[] val, int bits) {
assert (val.length <= bits);
int[] ret = new int[bits];
for (int i = bits - val.length, j = 0; i < bits; i++, j++) {
ret[i] = val[j];
}
return ret;
}
}