LoginSignup
10
9

More than 5 years have passed since last update.

Javaで最大公約数

Posted at

最大公約数

説明するまでもないですが、2つ以上の正の整数に共通な約数(公約数)のうち最大のものを最大公約数といいます。

これを簡単に求めるには

ユークリッドの互除法

を用います。

言葉だけだと難しく感じそうですが、プログラム的にはすごくシンプルになります。

最大公約数のコード

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Gcd {

    public static void main(String args[]) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String line = br.readLine();
        int[] numArray = parseInt(getSplitLine(line));

        int x;
        int y;
        if (numArray[0] > numArray[1]) {
            x = numArray[0];
            y = numArray[1];
        } else {
            x = numArray[1];
            y = numArray[0];
        }

        // ここからがユークリッドの互除法を用いた最大公約数を
        // 求める為の式
        int tmp;
        while ((tmp = x % y) != 0) {
            x = y;
            y = tmp;
        }

        System.out.println(y);
    }

    private static String[] getSplitLine(String line) {
        return line.split("\\s");
    }

    private static int[] parseInt(String[] line) {
        int[] numArray = new int[line.length];
        for (int i = 0; i < line.length; i++) {
            numArray[i] = Integer.parseInt(line[i]);
        }
        return numArray;
    }
}

解法

例:
147 と 105 の最大公約数は 21

これを解いていく方法としては、

147 % 105 = 1 あまり 42
105 % 42 = 2 あまり 21
42 % 21 = 2 あまり 0
よって、21が最大公約数となる。
※証明の観点ですともっと複雑になりますが、この方法で解いた結果が
 最大公約数となるという理解で十分だと思います。

10
9
1

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
10
9