분수 A/B
는 분자가 A
, 분모가 B
인 분수를 의미한다. A
와 B
는 모두 자연수라고 하자.
두 분수의 합 또한 분수로 표현할 수 있다. 두 분수가 주어졌을 때, 그 합을 기약분수의 형태로 구하는 프로그램을 작성하시오. 기약분수란 더 이상 약분되지 않는 분수를 의미한다.
첫째 줄과 둘째 줄에, 각 분수의 분자와 분모를 뜻하는 두 개의 자연수가 순서대로 주어진다. 입력되는 네 자연수는 모두 30,000 이하이다.
첫째 줄에 구하고자 하는 기약분수의 분자와 분모를 뜻하는 두 개의 자연수를 빈 칸을 사이에 두고 순서대로 출력한다.
2 7
3 5
31 35
-문제를 만든 사람: author5
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Code1735 {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] first=br.readLine().split(" ");
int firstup=Integer.valueOf(first[0]);
int firstdown=Integer.valueOf(first[1]);
String[] second=br.readLine().split(" ");
int secondup=Integer.valueOf(second[0]);
int seconddown=Integer.valueOf(second[1]);
br.close();
int down=firstdown*seconddown;
int up=firstup*seconddown+secondup*firstdown;
int div=gcd(up,down);
down=down/div;
up=up/div;
System.out.println(up+" "+down);
}
public static int gcd(int a,int b){
if(a%b==0){
return b;
}
return gcd(b,a%b);
}
}
GCD
함수를 이용해 재귀함수로 문제를 해결했다!