baru003のブログ

baruの雑記兼備忘録

Project Euler 0020

・問題リンクFind the sum of digits in 100!

・コメント
概要

n! means n  (n  1)  ...  3  2  1

For example, 10! = 10  9  ...  3  2  1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

100!(100の階乗)は明らかにintやlong型の扱える範囲を超える結果になってしまいます。

なのでBigIntegerを使って階乗計算を行った後、各桁を文字列の部分文字列として取り出してそれをint型にキャストして加算していきました。

今までlong型でも扱い切れないような大きい数を扱ったことがなかったので、

BigIntegerに少し触れる機会ができたのはよかったと思います。

階乗計算も再帰三項演算子を使うとすっきり書けていいですね。

おしまい。

・ソース

import java.math.BigInteger;

public class P0020 {

	public static void solve(String num) {
		int ans = 0;
		int length = num.length();
		for (int i = 0; i < length; i++) {
			ans += Integer.parseInt(num.substring(i, i + 1));
		}
		System.out.println(ans);
	}

	public static String factorial(String s) {
		BigInteger ans = BigInteger.valueOf(1);
		for (int i = 1; i <= Integer.parseInt(s); i++) {
			ans = ans.multiply(BigInteger.valueOf(i));
		}
		return ans.toString();
	}

	public static void main(String[] args) {
		String number = "100";
		solve(factorial(number));
	}
}