
-Code
import java.util.Scanner;
public class BOJ2485 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] nums = new int[t];
for (int i = 0; i < t; i++) {
nums[i] = sc.nextInt();
}
// 가로수 사이 거리들의 최대 공약수 구하기
int gcd = nums[1] - nums[0];
for (int i = 2; i < t; i++) {
gcd = getGcd(gcd, nums[i] - nums[i - 1]);
}
int start = nums[0];
int end = nums[t - 1];
int answer = 0;
// 최대값 전까지 최대 공약수 만큼 더하면서 갯수 새기
while (start <= end) {
answer++;
start += gcd;
}
System.out.println(answer - t);
}
private static int getGcd(int a, int b) {
if (b == 0) {
return a;
}
return getGcd(b, a % b);
}
}
위가 정답 코드이나 뭔가 개선 가능할 것 같이서 아래와 같이 개선했습니다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] nums = new int[t];
for (int i = 0; i < t; i++) {
nums[i] = sc.nextInt();
}
// 가로수 사이 거리들의 최대 공약수 구하기
int gcd = nums[1] - nums[0];
for (int i = 2; i < t; i++) {
gcd = getGcd(gcd, nums[i] - nums[i - 1]);
}
int start = nums[0];
int end = nums[t - 1];
// 시작점 부터 끝점까지의 거리 나누기 gcd 후 + 1이
// 총 가로수 설치 수
System.out.println((end - start) / gcd - t + 1);
}
private static int getGcd(int a, int b) {
if (b == 0) {
return a;
}
return getGcd(b, a % b);
}
}'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [백준/Java] 4134번 다음 소수 (0) | 2025.12.26 |
|---|---|
| [백준/Java] 34946번 셔틀 탈래 말래 탈래 말래 애매하긴 해 (0) | 2025.12.26 |
| [백준/Java] 1735번 분수 합 (0) | 2025.12.25 |
| [백준/Java] 34935번 오름차순과 비내림차순 (0) | 2025.12.25 |
| [백준/Java] 13241번 최소공배수 (0) | 2025.12.24 |