본문 바로가기

백준9506 - 약수들의 합 JS | Python 본문

개발/algorithm

백준9506 - 약수들의 합 JS | Python

자전하는명왕성 2023. 10. 20. 09:48

https://www.acmicpc.net/problem/9506

해당 문제는 특정 수 n이 주어질 때, n을 제외한 n의 약수의 합이 n과 같다면 예제와 같은 문자열을 만들어 반환,

그렇지 않은 경우는 n is NOT perfect.라는 문자열을 반환하는 문제다.

 

해결한 방식으로는 다음과 같다. 

먼저 약수를 담을 리스트를 만든다.

만약 n으로 6이 주어졌다고 한다면 반복문을 통해 1~3까지의 수만 6과 나누어 떨어지는지 계산한 뒤, 리스트에 추가한다.

6은 이미 무조건 약수일 뿐더러, 3을 초과하는 수는 6의 약수가 될 수 없기 때문에 반복문의 범위를 줄인다고 보면 된다.

 

이후 약수를 담은 리스트의 총합과 n의 값을 비교하여 출력 양식에 맞춰 출력한다.

 

파이썬 소스코드

import sys
temp = sys.stdin if sys.platform == 'linux' else open('입력.txt', 'r')
input_data = temp.read().splitlines()

def act (n) :
  # 약수를 담을 리스트
  arr = []
  for x in range(1, int(n/2)+1) :
    # 나누어질 시 리스트에 추가
    if n % x == 0 : arr.append(x)
  
  # 중괄호와 format() 메서드는 자바스크립트의 템플릿리터럴과 같이 동적 & 정적 요소를 함께 표현할 때 사용 가능
  if sum(arr) == n :
    return '{} = '.format(n) + ' + '.join(map(str,arr))
  else : 
    return '{} is NOT perfect.'.format(n)
      
def solution (data) :
  data.pop()
  # python에서는 lambda 를 통해 인자를 선언 후 사용할 수 있다
  result = list(map(lambda x : act(int(x)), data))
  print('\n'.join(result))
        
solution(input_data)

 

자바스크립트 소스코드

const fs = require("fs");
const input = fs
  .readFileSync(process.platform === "linux" ? "/dev/stdin" : "입력.txt")
  .toString()
  .trim()
  .split("\n");

const act = (n) => {
  const arr = [];
  for (let i = 1; i <= ~~(n / 2); i++) {
    n % i == 0 && arr.push(i);
  }

  return +n === arr.reduce((a, c) => a + c)
    ? `${n} = ` + arr.join(" + ")
    : `${n} is Not perfect.`;
};

function solution(data) {
  data.pop();
  const result = data.map((el) => act(el));
  console.log(result.join("\n"));
}

solution(input);
Comments