Jam's story
[프로그래머스] 최대공약수와 최소공배수 본문
import java.util.*;
class Solution {
public static int[] solution(int n, int m) {
int[] answer = new int[2];
int max=0 ,num=0; ;
//두수중에서 작은수는
int twoMax=(n>m)?m:n;
for(int i=1; i<=twoMax; i++){
if(twoMax%i==0 && m%i==0) {
num=i;
num=max<num? num:max;
System.out.println("num: "+num);
}
}//for-i
int b=num*(n/num)*(m/num);
answer[0]=num;
answer[1]=b;
return answer;
}
public static void main(String[] args){
solution(3,12);
}
}
import java.util.*;
class Solution {
public static int[] solution(int n, int m) {
int[] answer = new int[2];
int max=0 ,num=0;
//두수중에서 작은수는
int twoMax=(n>m)?m:n;
for(int i=1; i<=twoMax; i++){
if(twoMax%i==0 && m%i==0) {
num=i;
num=max<num? num:max;
System.out.println("num: "+num);
}
}//for-i
int b=0;
if(num==1){b=n*m; }
else{
b=n*m/num;
}
answer[0]=num;
answer[1]=b;
return answer;
}
public static void main(String[] args){
solution(3,12);
}
}

유클리드 호제법 사용
두 수의 나머지가 0이 될때까지
계속해서 반복하며 나머지를 구하는 방식이라고 생각하면 된다.
import java.util.*;
class Solution {
public int[] solution(int n, int m) {
int a = Math.max(n, m);
int b = Math.min(n, m);
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
//최대 공배수 = 두 수의 곱 / 최대공약수
return new int[] { a, n * m / a };
}
}
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 휴대폰 번호 가리기 (0) | 2022.08.13 |
---|---|
[프로그래머스] 콜라츠 추측 (0) | 2022.08.12 |
[프로그래머스] 이상한 문자 만들기 (0) | 2022.08.09 |
[프로그래머스] 약수의 합 (0) | 2022.08.06 |
[프로그래머스] 시저 암호 (0) | 2022.08.05 |