약수의 합

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// https://programmers.co.kr/learn/courses/30/lessons/12928
function solution(n) {
if (n == 0 || n == 1) {
return n;

let arr = [1, n];
console.log(Math.sqrt(n));
for (let index = 2; index <= Math.sqrt(n); index++) {
if (n % index == 0) {
arr.push(index);
if (index == Math.sqrt(n)) {
} else {
arr.push(n / index);
}
}
}
console.log(arr);
return arr.reduce((prev, curr) => {
console.log(prev, curr);
return curr + prev;
}, 0);
}
result = solution(12); //28

해설

  • 정수를 입력받으면 모든 약수의 합을 반환한다
  • 0, 1인 경우 바로 반환한다
  • 무조건 약수인 1과 자기자신으로 약수가 저장될 배열을 초기화한다
  • 2부터 n의 제곱근까지 반복문을 돌면서 나누어 떨어지는지 판단한다
  • 나누어 떨어지면 약수 배열에 추가한다
  • 약수는 항상 세트로 존재하기 때문에, 제곱근의 경우가 아니라면 n / index 도 약수로 추가한다
  • reduce로 약수배열의 합을 구한다
Author

chinsung

Posted on

2020-09-18

Updated on

2021-08-04

Licensed under

댓글