프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 설명
첫 번째 분수의 분자와 분모를 뜻하는 numer1, denom1, 두 번째 분수의 분자와 분모를 뜻하는 numer2, denom2가 매개변수로 주어집니다. 두 분수를 더한 값을 기약 분수로 나타냈을 때 분자와 분모를 순서대로 담은 배열을 return 하도록 solution 함수를 완성해보세요.
제한사항
입출력 예
- 0 < numer1, denom1, numer2, denom2 < 1,000
입출력 예
numer1 | denom1 | numer2 | denom2 | result |
1 | 2 | 3 | 4 | [5, 4] |
9 | 2 | 1 | 3 | [29, 6] |
입출력 예 설명
입출력 예 #1
- 1 / 2 + 3 / 4 = 5 / 4입니다. 따라서 [5, 4]를 return 합니다.
입출력 예 #2
- 9 / 2 + 1 / 3 = 29 / 6입니다. 따라서 [29, 6]을 return 합니다.
코드
class Solution {
fun gcd(a: Int, b: Int): Int {
if (a % b == 0) {
return b
}
return gcd(b, a % b)
}
fun lcm(a: Int, b: Int): Int {
return a * b / gcd(a, b)
}
fun solution(numer1: Int, denom1: Int, numer2: Int, denom2: Int): IntArray {
val parent = lcm(denom1, denom2)
val child = numer1 * (parent / denom1) + numer2 * (parent / denom2)
val g = gcd(parent, child)
return if (g != 1) intArrayOf(child / g, parent / g) else intArrayOf(child, parent)
}
}
풀이
유클리드 호제법
유클리드 互 除 法 / Euclidean algorithm 두 양의 정수, 혹은 두 다항식의 최대공약수 를 구
namu.wiki
최대공약수
最 大 公 約 數 · greatest common divisor(factor), GCD 정수의 성질 중 하나. 초
namu.wiki
최소공배수
最 小 公 倍 數 · least common multiple, LCM 초등학교 5학년 때 약수 (diviso
namu.wiki
기약분수
旣 約 分 數 / Irreducible fraction 분자 와 분모 가 (둘의 공약수가 밖에 없는) 서로소
namu.wiki
'프로그래머스' 카테고리의 다른 글
[프로그래머스][Kotlin] 겹치는 선분의 길이 (0) | 2024.08.06 |
---|---|
[프로그래머스][Kotlin] 유한소수 판별하기 (0) | 2024.08.06 |
[프로그래머스][Kotlin] 종이 자르기 (0) | 2024.08.01 |