문제
머쓱이네 피자가게는 피자를 여섯 조각으로 잘라 줍니다. 피자를 나눠먹을 사람의 수 n이 매개변수로 주어질 때, n명이 주문한 피자를 남기지 않고 모두 같은 수의 피자 조각을 먹어야 한다면 최소 몇 판을 시켜야 하는지를 return 하도록 solution 함수를 완성해보세요.
class Solution {
public int solution(int n) {
if (n % 6 == 0) {
return n / 6;
} else if (n % 3 == 0) {
return (n * 2) / 6;
} else if (n % 2 == 0) {
return (n * 3) / 6;
} else {
return n;
}
}
}
최소공배수와 최대공약수 사이에는 다음과 같은 관계가 있으므로...
LCM(a,b)=\frac{a\times b}{GCD(a,b)}
개선해보면 이렇게 되긴 한다.
\frac{LCM(n,6)}{6} =\frac{n\times6}{GCD(n,6)\times6} =\frac{n}{GCD(n,6)}
class Solution {
public int solution(int n) {
return n / gcd(n, 6);
}
public int gcd(int a, int b) {
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
}