0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

競技プログラミングの問題を解いている際に、最小公倍数か最大公約数を求める必要に迫られる場合がある。
今までは、先人らのコードをコピペして使わせて頂いていたのだが、モラル的に良くない気がしたので自分用に書いたため、貼っておく。
型などlongの方が良いかも。
最大公約数はユークリッドの互除法より得られ、また最小公倍数は元の2数をかけて最大公約数で割ったものから得られる。

9,18の場合...最大公約数は9,これらをかけて9で割るので18が最小公倍数となる。


// 最大公約数
public static int Gcd(int a, int b)
    {
        var x = 0;

        while (true)
        {
            // 割り切れたら
            if (a % b == 0)
            {
                return b;
            }
            else
            {
                x = a % b;
                a = b;
                b = x;

            }
        }
        
    }
// 最小公倍数
    public static int Lcm(int a, int b)
    {
        var x = Gcd(a, b);

        return a * b / x;
    }

呼び出し方としては、こんな感じで(適当にMain関数の中で呼んだけど)指定してあげてね。


using System;

    public static void Main()
    {

      var a = 10;
      var b = 20;
      Console.WriteLine(Gcd(a,b));
      Console.WriteLine(Lcm(a,b));

    }

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?