본문 바로가기

PS/Algorithms

[Java] Euclidean-Algorithm

https://ko.wikipedia.org/wiki/%EC%9C%A0%ED%81%B4%EB%A6%AC%EB%93%9C_%ED%98%B8%EC%A0%9C%EB%B2%95

 

유클리드 호제법 - 위키백과, 우리 모두의 백과사전

유클리드 호제법(-互除法, Euclidean algorithm) 또는 유클리드 알고리즘은 2개의 자연수 또는 정식(整式)의 최대공약수를 구하는 알고리즘의 하나이다. 호제법이란 말은 두 수가 서로(互) 상대방 수를

ko.wikipedia.org

위키피디아 움짤만 봐도 바로 이해가능

import java.util.*;
import java.io.*;

public class euclidean {
    static FastScanner fs = new FastScanner();
    static PrintWriter pw = new PrintWriter(System.out);

    public static void main(String[] args) {
        int a = fs.nextInt(), b = fs.nextInt();
        pw.println(euc(Math.min(a, b), Math.max(a, b)));

        pw.close();
    }

    static int euc(int a, int b){
        if (b % a == 0) return a;
        else return euc(b % a, a);
    }

    // ----------input function----------

    static void sort(int[] a) {
        ArrayList<Integer> L = new ArrayList<>();
        for (int i : a)
            L.add(i);
        Collections.sort(L);
        for (int i = 0; i < a.length; i++)
            a[i] = L.get(i);
    }

    static class FastScanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer("");

        String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        int[] readArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        long nextLong() {
            return Long.parseLong(next());
        }
    }
}

'PS > Algorithms' 카테고리의 다른 글

[Java] HashMap vs TreeMap  (0) 2022.06.09
[Java] Pollard-Rho Algorithm  (0) 2022.05.20
[Java] Millar-Rabin primality test  (0) 2022.05.19
[Java] LCA (Lowest Common Ancestor)  (0) 2022.05.17
[Java] Index Tree / Segment Tree Lazy Propagation  (0) 2022.03.15