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

ABC253-D FizzBuzz Sum Hard


問題へのリンク


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("10 3 5");
            //22
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("1000000000 314 159");
            //495273003954006262
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] wkArr = InputList[0].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        long N = wkArr[0];
        long A = wkArr[1];
        long B = wkArr[2];

        long SumAll = DeriveTousaSuuretuSum(1, 1, N);

        long SumA = DeriveTousaSuuretuSum(A, A, N / A);
        long SumB = DeriveTousaSuuretuSum(B, B, N / B);

        long LCM = DeriveLCM2(A, B);
        long SumLCM = DeriveTousaSuuretuSum(LCM, LCM, N / LCM);

        Console.WriteLine(SumAll - SumA - SumB + SumLCM);
    }

    // 初項と公差と項数を引数として、等差数列の和を返す
    static long DeriveTousaSuuretuSum(long pSyokou, long pKousa, long pKouCnt)
    {
        long Makkou = pSyokou + pKousa * (pKouCnt - 1);
        long wkSum = pSyokou + Makkou;
        long Result = wkSum * pKouCnt;
        Result /= 2;
        return Result;
    }

    // 2つの数のLCMを求める
    static long DeriveLCM2(long p1, long p2)
    {
        long GCD = DeriveGCD(p1, p2);
        return (p1 / GCD) * p2;
    }

    // ユークリッドの互除法で2数の最大公約数を求める
    static long DeriveGCD(long pVal1, long pVal2)
    {
        long WarareruKazu = pVal2;
        long WaruKazu = pVal1;

        while (true) {
            long Amari = WarareruKazu % WaruKazu;
            if (Amari == 0) return WaruKazu;
            WarareruKazu = WaruKazu;
            WaruKazu = Amari;
        }
    }
}


解説

包除原理をふまえて、
等差数列の和の公式を使ってます。