BOJ 17087. 숨바꼭질 6
BOJ 17087. 숨바꼭질 6
풀이
첫 줄에 N(동생의 수), S(현재 위치)가 주어지고
둘째 줄에 동생들의 위치가 주어진다.
3 3 // 동생의수 3, 현재위치 3
1 7 11 // 동생들의 위치
현재 위치 3에서 동생들의 위치 (1, 7, 11)까지의 각각 거리를 계산하여 배열에 저장한다.
배열에 저장된 현재 위치와의 거리 차이들의 최대 공약수가 이동할 수 있는 최대 거리 D가 된다.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int s = sc.nextInt();
int[] distances = new int[n];
for (int i = 0; i < n; i++) {
int b = sc.nextInt();
distances[i] = Math.abs(s - b);
}
int result = distances[0];
for (int i = 1; i < n; i++) {
result = getGCD(result, distances[i]);
}
System.out.println(result);
sc.close();
}
static int getGCD(int a, int b) {
if (b == 0) {
return a;
} else {
return getGCD(b, a % b);
}
}
}
import kotlin.math.abs
fun main() {
val (n, s) = readLine()!!.split(" ")
val distances = readLine()!!.split(" ")
.map { it.toInt() }
.map { s.toInt() - it }
.map { abs(it) }
var result = distances[0]
(1 until n.toInt()).forEach {
result = getGCD(result, distances[it])
}
println(result)
}
fun getGCD(a: Int, b: Int): Int = if (b == 0) a else getGCD(b, a % b)
풀이소스
github.com/beomjo/algorithm-study/blob/main/BOJ/java/17087.java github.com/beomjo/algorithm-study/blob/main/BOJ/kotlin/17087.kt