AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

NTL_1_C: Least Common Multiple


問題へのリンク


C#のソース

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

// Q086 最小公倍数 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_1_C&lang=jp
class Program
{
    static string InputPattern = "InputX";

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

        if (InputPattern == "Input1") {
            WillReturn.Add("3");
            WillReturn.Add("3 4 6");
            //12
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("4");
            WillReturn.Add("1 2 3 5");
            //30
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

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

        long CurrLCM = AArr[0];
        for (int I = 1; I <= AArr.GetUpperBound(0); I++) {
            long CurrGCD = DeriveGCD(CurrLCM, AArr[I]);
            CurrLCM = CurrLCM * AArr[I] / CurrGCD;
        }
        Console.WriteLine(CurrLCM);
    }

    //ユークリッドの互除法で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;
        }
    }
}


解説

A*B = GCD(A,B) * LCM(A,B)
なことをふまえて、順番に、LCMを求めてます。