当前位置:首页 » Project Euler » 详细页

Powerful digit sum 题号:56 难度: 5 中英对照

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?

Solution

要求 $~a^b,a,b < 100~$的各位数字和的最大值,只需要对 $~a, b~$进行两层循环即可。 各位数字之和的算法:将数值转换成字符数组,然后将各字符转换成整数求和即可。

Code


import java.math.BigInteger;

public final class p056 {

    public static void main(String[] args) {
        long start = System.nanoTime();
        long result = run();
        long end = System.nanoTime();
        System.out.println(result);
        System.out.println((end - start) / 1000000 + "ms");
    }

    public static long run() {
        int max = 0;
        for (int a = 1; a < 100; a++) {
            for (int b = 1; b < 100; b++) {
                BigInteger pow = BigInteger.valueOf(a).pow(b);
                max = Math.max(digitSum(pow), max);
            }
        }
        return max;
    }

    private static int digitSum(BigInteger n) {
        int sum = 0;
        String s = n.toString();
        for (int i = 0; i < s.length(); i++) {
            sum += Integer.parseInt( String.valueOf(s.charAt(i)));
        }
        return sum;
    }
}
972
183ms