티스토리 뷰
코딩테스트 연습 - 최대공약수와 최소공배수 | 프로그래머스 (programmers.co.kr)
코딩테스트 연습 - 최대공약수와 최소공배수
두 수를 입력받아 두 수의 최대공약수와 최소공배수를 반환하는 함수, solution을 완성해 보세요. 배열의 맨 앞에 최대공약수, 그다음 최소공배수를 넣어 반환하면 됩니다. 예를 들어 두 수 3, 12의
programmers.co.kr
나의 코드
const greatestCommonFactors = (n,m) => {
let commonFactorsArr = [];
let countN = 1;
let originalN = n;
let smallerNum = n >= m? m : n;
while(smallerNum > 0){
if(n % smallerNum === 0 && m % smallerNum === 0){
break;
}
smallerNum--;
}
return smallerNum;
}
const leastCommonMultiples = (n,m) => {
const num = greatestCommonFactors(n, m);
return num * (n/num) * (m/num);
}
const solution = (n, m) => {
let answer = [greatestCommonFactors(n,m),leastCommonMultiples(n,m)];
return answer;
}
smallerNum-- 때문에 조금 지연이 된다
나의 코드 2
const greatestCommonFactors = (n,m) => {
let smallerNum = n >= m? m : n;
let biggerNum = n <= m? m : n;
let r = 0;
while(biggerNum % smallerNum !== 0){
r = biggerNum % smallerNum;
biggerNum = smallerNum;
smallerNum = r;
}
return smallerNum;
}
const leastCommonMultiples = (n,m) => {
const num = greatestCommonFactors(n, m);
return num * (n/num) * (m/num);
}
const solution = (n, m) => {
let answer = [greatestCommonFactors(n,m),leastCommonMultiples(n,m)];
return answer;
}
유클리드를 쓰면 훨씬 빨라진다
'개발자 > 프로그래머스 알고리즘' 카테고리의 다른 글
코딩테스트 연습 - 3진법 뒤집기 | 프로그래머스 js ★★☆☆☆ (0) | 2022.02.07 |
---|---|
코딩테스트 연습 - 크레인 인형뽑기 게임 | 프로그래머스 js ★★★☆☆ (0) | 2022.02.07 |
코딩테스트 연습 - 예산 | 프로그래머스 js ★★☆☆☆ (0) | 2022.02.03 |
코딩테스트 연습 - 실패율 | 프로그래머스 js ★★★★☆ (0) | 2022.02.03 |
코딩테스트 연습 - 모의고사 | 프로그래머스 js ★★★★☆ (0) | 2022.01.27 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 에러
- elasticsearch
- GraphQL
- function
- 프로그래머스
- nodemon
- Callback
- NPM
- 코드캠프
- 콜백
- arrow
- js
- 공부법
- 도커
- yarn
- 명령어
- error
- typeorm
- 백틱
- postman
- 코딩습관
- Playground
- Rest
- arrowfunction
- 호이스팅
- 독커
- Console
- axios
- Spread
- docker
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함