どーも、みつおです。
2^1000とかlong型で表せませんからw
今回も「C#でプロジェクトオイラーを解く(問題13「大きな数の足し算」)」と同様にBigIntegerを使う。
BigIntegerの使い方は、「[C#]桁数が非常に大きい数値の計算 – BigIntegerを利用したInt64を超える数値の計算」を参考にすればいいよ。
問題
2^15 = 32768 であり, 各位の数字の和は 3 + 2 + 7 + 6 + 8 = 26 となる.
同様にして, 2^1000 の各位の数字の和を求めよ.
注: Problem 20 も各位の数字の和に関する問題です。解いていない方は解いてみてください。
出典:Problem16
解答
using System;
using System.Numerics;
namespace Problem16
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Solve());
            Console.ReadLine();
        }
        private static int Solve()
        {
            int ret = 0;
            BigInteger bigint = new BigInteger();
            //2^1000を求める
            bigint = (BigInteger)Math.Pow(2, 1000);
            //2^1000を文字列に変換
            string strdata = bigint.ToString();
            //桁数分ループ
            for(int i = 0;i < strdata.Length;i++)
            {
                //各桁を足していく
                ret += int.Parse(strdata[i].ToString());
            }
            return ret;
        }
    }
}
出力
1366
 
  
  
  
  


コメント