AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC357-D 88888888


問題へのリンク


C#のソース

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("5");
            //55555
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("9");
            //1755646
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("10000000000");
            //468086693
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    const long Hou = 998244353;

    static void Main()
    {
        List<string> InputList = GetInputList();
        long N = long.Parse(InputList[0]);

        long Kouhi = 1;
        for (long I = 1; I <= N.ToString().Length; I++) {
            Kouhi *= 10;
            Kouhi %= Hou;
        }

        long Syokou = N;
        long Kousuu = N;

        long TouhisuuretuSum = DeriveTouhisuuretuSum(Syokou, Kouhi, Kousuu, Hou);
        Console.WriteLine(TouhisuuretuSum);
    }

    // 初項,公比,項数,法を引数とし、等比数列の和を返す(法が逆元を持たなくても可)
    static long DeriveTouhisuuretuSum(long pSyokou, long pKouhi, long pKousuu, long pHou)
    {
        pSyokou %= pHou;

        // 項数が1の場合
        if (pKousuu == 1) {
            return pSyokou;
        }

        // 項数が奇数の場合
        if (pKousuu % 2 == 1) {
            long WillReturn = pSyokou;
            WillReturn += DeriveTouhisuuretuSum(pSyokou * pKouhi, pKouhi, pKousuu - 1, pHou);
            WillReturn %= pHou;
            return WillReturn;
        }

        // 項数が偶数の場合
        long SumLeft = DeriveTouhisuuretuSum(pSyokou, pKouhi, pKousuu / 2, pHou);
        SumLeft %= pHou;

        long SumRight = SumLeft * DeriveBekijyou(pKouhi, pKousuu / 2, pHou);
        SumRight %= pHou;

        return (SumLeft + SumRight) % pHou;
    }

    // 繰り返し2乗法で、(NのP乗) Mod Mを求める
    static long DeriveBekijyou(long pN, long pP, long pM)
    {
        long CurrJyousuu = pN % pM;
        long CurrShisuu = 1;
        long WillReturn = 1;

        while (true) {
            // 対象ビットが立っている場合
            if ((pP & CurrShisuu) > 0) {
                WillReturn = (WillReturn * CurrJyousuu) % pM;
            }

            CurrShisuu *= 2;
            if (CurrShisuu > pP) return WillReturn;
            CurrJyousuu = (CurrJyousuu * CurrJyousuu) % pM;
        }
    }
}


解説

5の場合
5 + 50 + 500 + 5000 + 50000
でこれは、
初項5、公比10、項数5の等比数列の和になります。