-
알고리즘 하드코딩 장인 [프로그래머스] 약수의 개수와 덧셈 (코드 간결화)Algorithm 2023. 4. 11. 13:21728x90
Q. 두 정수 left와 right가 매개변수로 주어집니다. left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요
// 두 정수 left와 right가 매개변수로 주어집니다. left부터 right까지의 모든 수들 중에서, 약수의 개수가 짝수인 수는 더하고, // 약수의 개수가 홀수인 수는 뺀 수를 return 하도록 solution 함수를 완성해주세요. function solution(left, right) { let answer = 0; let arr = []; //left부터 right까지 정수의 약수를 차례로 담을 array let count = []; //left부터 right까지 정수의 약수가 각각 몇개씩인지 담을 array for (let a = left; a <= right; a++) { //a가 13,14,..17 left부터 right까지 값이 하나씩 a에 대입되어 약수를 구할 것이다 for (let i = 0; i <= a; i++) for (let j = 0; j <= a; j++) //a의 약수를 구하기 위해서 0부터 a까지 정수 중에 서로를 곱했을 때(i*j) a가 되는 정수가 a의 약수임. if (i * j === a) { arr.push(i); arr.push(j); } let set = [...new Set(arr)]; //중복 제거. console.log(a, ":", set); count.push(set.length); //각각 약수가 몇개인지 count 배열에 push. console.log(set.length); arr = []; //배열 초기화. } console.log(count); // [13,14,15,16,17,18] for (let i = 0; i < count.length; i++) { //각각의 count요소들이 짝수인지 홀수인지 판별해서 더하거나 뺀다. if (count[i] % 2 === 0) { answer += left + i; console.log(i, answer); } else { answer -= left + i; console.log(i, answer); } } return answer; } console.log(solution(13, 17));
어제부터 정우님과 코테 스터디를 하고있다. 그래서 최대한 지저분한 나의 코드를 이해할 수 있게 주석을 달았다..
쓸데없이 변수를 많이 만들었고, for문을 세개나 쓸 필요가 없었는데 불필요한 코드가 많았었다.
간결화 작업
내 코드에 대해 chatGPT에게 받은 조언
arr 배열은 set 배열에서 중복된 값을 제거하기 위한 용도로 사용되는데, 이를 위해 매번 빈 배열로 초기화하는 부분이 불필요합니다. 초기화하는 대신, 반복문의 바깥에서 arr 배열을 정의하고, 반복문 안에서는 arr 배열에 값을 추가하는 것으로 수정할 수 있습니다.
arr 배열은 set 배열에서 중복된 값을 제거하기 위한 용도로 사용되는데, 이를 위해 매번 빈 배열로 초기화하는 부분이 불필요합니다.
-> arr배열에 약수를 계속 추가하고 인덱스 하나가 끝날 때 마다 for문을 초기화시켰었다. 이 부분을 첫번째 for문에 선언하면서 초기화하는 부분을 제거할 수 있다.
function solution_(left, right) { let answer = 0; for (let a = left; a <= right; a++) { let arr = []; //left부터 right까지 정수의 약수를 차례로 담을 array for (let i = 1; i <= a; i++) { if (a % i === 0) { arr.push(i); } } //나누었을 때 나누어 떨어지는 수가 약수임. a%i===0일 때 arr에 추가함으로서 간결화 let set = [...new Set(arr)]; //중복 제거. //count배열을 만들 필요 없이 바로 for문 내에서 덧셈or뺄셈 연산 if (set.length % 2 === 0) { answer += a; } else { answer -= a; } } // for문이 여기서 끝남 return answer; }
a % i === 0 이라면 a는 i로 나누어 떨어지는 것이므로, i는 a의 약수임을 알 수 있습니다.
728x90'Algorithm' 카테고리의 다른 글
HackerRank 문제 해석, 풀이 Apple and Orange-Java script (0) 2023.04.12 HackerRank 문제 해석, 풀이 Grading Student - Java script (0) 2023.04.12 HackerRank 문제 해석, 풀이 Plus Minus- Java script (0) 2023.04.06 [알고리즘풀기] 프로그래머스 로그인성공? (0) 2023.03.30 [알고리즘풀기] 프로그래머스 문자열 나누기 Java script (0) 2023.03.28