どーも、みつおです。
プロジェクトオイラーってたまに、巨大すぎる数値を計算させるときあるよね。
BigIntegerの使い方は、「[C#]桁数が非常に大きい数値の計算 – BigIntegerを利用したInt64を超える数値の計算」を参考にすればいいよ。
問題
n × (n – 1) × … × 3 × 2 × 1 を n! と表す.
例えば, 10! = 10 × 9 × … × 3 × 2 × 1 = 3628800 となる.
この数の各桁の合計は 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 である.では, 100! の各位の数字の和を求めよ.
注: Problem 16 も各位の数字の和に関する問題です。解いていない方は解いてみてください。
出典:Problem20
解答
using System;
using System.Numerics;
namespace Problem20
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Solve());
Console.ReadLine();
}
private static int Solve()
{
int ret = 0;
//100!を求める
BigInteger num = 1;
for (int i = 2; i <= 100; i++) num *= i;
//各桁を足し合わせる
while (num > 0)
{
ret += (int)(num % 10);
num /= 10;
}
return ret;
}
}
}
出力
648