[알고리즘]/백준

백준 17087 자바 - 숨바꼭질6

broship 2021. 7. 3. 19:33

문제


 

 

문제해결


- 자신의 위치와 동생의 위치의 거리를 배열에 담는다

- 배열을 돌면서 모든 수의 최대공약수를 구하면 된다

import java.util.Scanner;

public class B17087 {

    public static int gcd(int a, int b){
        if (b==0) return a;
        return gcd(b, a%b);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int s = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            int tmp = sc.nextInt();
            arr[i] = Math.abs(s - tmp);
        }

        int result = arr[0];
        for (int i = 1; i < n; i++) {
            result = gcd(result, arr[i]);
        }
        System.out.println(result);
    }
}