C#でプロジェクトオイラーを解く(問題48「自身のべき乗(self powers)」)

プロジェクトオイラー
Pocket

どーも、みつおです。

問題

次の式は, 1^1 + 2^2 + 3^3 + … + 10^10 = 10405071317 である.

では, 1^1 + 2^2 + 3^3 + … + 1000^1000 の最後の10桁を求めよ.

出典:Problem48

解答

using System;
using System.Numerics;

namespace Problem48
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Solve());
            Console.ReadLine();
        }

        private static string Solve()
        {
            string ret = "";
            BigInteger sum = 0;

            // 1^1 + 2^2 + 3^3 + ... + 1000^1000
            for (int i = 1; i <= 1000; i++)
            {
                sum += BigInteger.Pow(i, i);
            }

            //最後の10桁を取得
            ret = sum.ToString().Substring(sum.ToString().Length - 10, 10);
       
            return ret;
        }
    }
}

 

出力

9110846700

コメント

タイトルとURLをコピーしました